我需要针对 XSD 验证 XML 文件。XML 将从 URL 下载,我将其保存为 StremReader 或 XmlDocument。XSD 将作为 nvarchar(max) 从数据库返回。我被禁止在本地保存文件。有没有人如何处理这种情况的例子?我正在尝试这种方式,但我得到了 XmlException“缺少根元素”。
public void voltaXsd_em_StreamReader()
{
// strArquivoInteiro will contain the XSD comming from database
// as nvarchar(max) but I make simpler here.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\file.xsd");
string strArquivoInteiro = xmlDoc.OuterXml;
byte[] byteArray = Encoding.ASCII.GetBytes(strArquivoInteiro);
MemoryStream streamXSD = new MemoryStream(byteArray);
StreamReader readerXsd = new StreamReader(streamXSD);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationEventHandler += this.ValidationEventHandler;
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add("schema.xsd", XmlReader.Create(readerXsd));
settings.CheckCharacters = true;
XmlReader XmlValidatingReader = XmlReader.Create(@"C:\file.xml", settings);
XmlTextReader Reader = new XmlTextReader(@"file.xml");
XmlSchema Schema = new XmlSchema();
// Exactly here I am getting the exception
// "Root element is missing" and I do not know why.
Schema = XmlSchema.Read(readerXsd, ValidationEventHandler);
XmlValidatingReader ValidatingReader = new XmlValidatingReader(Reader);
//// 6- Setar o tipo de validação para o objeto XmlValidationReader
ValidatingReader.ValidationType = ValidationType.Schema;
//// 7- Adicionar Schema a coleção de Schemas XmlValidationReader
ValidatingReader.Schemas.Add(Schema);
try
{
//---------------
XmlValidatingReader.Read();
XmlValidatingReader.Close();
//// 8- Adicionar o endereço do ValidationEventHandler ao ValidationEventHandler do XmlValidationReader
ValidatingReader.ValidationEventHandler += ValidationEventHandler;
//9- Validar cada nó
while ((ValidatingReader.Read()))
{
}
ValidatingReader.Close();
}
catch (Exception ex)
{
ValidatingReader.Close();
XmlValidatingReader.Close();
}
}
private void ValidationEventHandler(object sender, ValidationEventArgs args)
{
bool blnXmlValido;
if (args.Severity == XmlSeverityType.Warning)
{
blnXmlValido = false;
}
else if (args.Severity == XmlSeverityType.Error)
{
blnXmlValido = false;
}
else if (!(string.IsNullOrEmpty(args.Exception.ToString())))
{
blnXmlValido = false;
}
if ((args.Exception != null))
{
}
}