如何在运行时验证xml对xsd而不保存本地文件夹上的文件?

时间:2010-06-18 20:02:04

标签: c# xsd xml-validation

我需要针对XSD验证XML文件。 XML将从URL下载,我将其保留为StremReader或XmlDocument。 XSD将从DataBase返回为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))
        {
        }
    }

1 个答案:

答案 0 :(得分:1)

如果没有看到您发送的xml示例,这有点难以调试。您是否确认正在读入的xml文档包含一个包含所有其他标记的根元素标记?

当您的xml缺少根标记以及xml文档为空时,会发生此错误。

同时验证您的流操作是否设置为流的开头。