不同类型的XML验证

时间:2016-04-28 15:18:48

标签: c# xml xsd

我正在寻找一些东西来验证我们针对它发送的XML。我遇到了这三个,但只有一个似乎工作'我猜测有一个标记和问题的原因是其他人不知道,但是想知道什么是最好的使用方法,除了这样做之外,区别于这三个。

XML

    <?xml version="1.0" encoding="UTF-8"?>
<Person>
    <Forename>John</Forename>
</Person>

XSD

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xs:schema 
  xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  elementFormDefault="qualified" version="0.2">
  <xs:annotation>
    <xs:documentation>
    </xs:documentation>
  </xs:annotation>
  <xs:element name ="Person">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Forename" type="xs:string"/>
        <xs:element name="Surname" type="xs:string"/>
        <xs:element name="Middlename" type="xs:string" minOccurs="0"/>
     </xs:sequence>
   </xs:complexType>
  </xs:element>
</xs:schema>

第一个标志是一个错误,该符号元素是预期的但不是我期望的XML。

class XPathValidation
    {
        static void Main()
        {
            XmlSchemaSet schemas = new XmlSchemaSet();
            schemas.Add("", XmlReader.Create(@"C:\test\test.xsd"));

            XDocument doc = XDocument.Load(@"C:\test\test.xml");



            Console.WriteLine("Validating doc1");
            bool errors = false;
            doc.Validate(schemas, (o, e) =>
            {
                Console.WriteLine("{0}", e.Message);
                errors = true;
            });
            Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");

            Console.ReadKey();
        }


    }

这两个都只是运行并且什么都不返回。

class XmlSchemaSetExample
    {
        static void Main()
        {
            XmlReaderSettings booksSettings = new XmlReaderSettings();
            booksSettings.Schemas.Add("http://www.w3.org/2001/XMLSchema", @"C:\test\test.xsd");
            booksSettings.ValidationType = ValidationType.Schema;
            booksSettings.ValidationEventHandler += new ValidationEventHandler(booksSettingsValidationEventHandler);

            XmlReader books = XmlReader.Create(@"C:\test\test.xml", booksSettings);

            while (books.Read()) { }

            Console.ReadKey();
        }

        static void booksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Warning)
            {
                Console.Write("WARNING: ");
                Console.WriteLine(e.Message);
            }
            else if (e.Severity == XmlSeverityType.Error)
            {
                Console.Write("ERROR: ");
                Console.WriteLine(e.Message);
            }
        }
    }

class XPathValidation
{
    static void Main()
    {
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add("http://www.w3.org/2001/XMLSchema", @"C:\test\test.xsd");
            settings.ValidationType = ValidationType.Schema;

            XmlReader reader = XmlReader.Create(@"C:\test\test.xml", settings);
            XmlDocument document = new XmlDocument();
            document.Load(reader);

            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

            // the following call to Validate succeeds.
            document.Validate(eventHandler);


            // the document will now fail to successfully validate
            document.Validate(eventHandler);

            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    static void ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        switch (e.Severity)
        {
            case XmlSeverityType.Error:
                Console.WriteLine("Error: {0}", e.Message);
                break;
            case XmlSeverityType.Warning:
                Console.WriteLine("Warning {0}", e.Message);
                break;
        }

    }
}

感谢您的信息,仍在学习这一切。

1 个答案:

答案 0 :(得分:1)

我认为后两个不起作用,因为当您将架构添加到targetNamespace时,您为XmlReaderSettings提供的值不正确。这应该是一个空字符串,因为您的XML没有名称空间(或null,如per the docs,这将从模式中推断出名称空间。)

哪种更好,这取决于您的要求。如果只是为了验证它,那么使用XmlReader的选项2是首选,因为它不会花费将整个XML加载到您随后丢弃的DOM中。

如果确实需要使用DOM查询XML,XDocument / LINQ to XML API(选项1)是一个比旧的XmlDocument API更好,更现代的API(选项3) )。

相关问题