0

我正在尝试使用 XSD 架构验证 XML 文件,并且我想确定使用 XmlReaderSettings 及其 ValidationEventHandler 存在特定属性。

这是我正在尝试做的一个例子。每个元素都有两个属性,“this”和“that”。如果缺少或拼写错误,我想提出一个例外。目前,ValidationEventHandler 仅在元素名称无效时引发异常。

XML 文件:

<Addresses>
  <Address this="fu1" that="bar" />
  <Address this="fu2" />
  <Address thiss="fu3" that="bar" />
</Addresses>

XSD 文件:

<?xml version="1.0" encoding="iso-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:attribute name="this" type="xs:string"/>
<xs:attribute name="that" type="xs:string"/>

<xs:element name="Address">
  <xs:complexType>
    <xs:attribute ref="this" use="required"></xs:attribute>
    <xs:attribute ref="that" use="required"></xs:attribute>
  </xs:complexType>
</xs:element>

<xs:element name="Addresses">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="Address" maxOccurs="unbounded">
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

C#代码:

using System.Xml;
using System.Xml.Schema;

namespace test_validation
{
    class Program
    {
        static void Main(string[] args)
        {
            string xsdpath = @"test.xsd";
            string xmlpath = @"test.xml";

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.Schemas.Add(null, xsdpath);
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationEventHandler += new ValidationEventHandler(settingsValidationEventHandler);

            XmlReader reader = XmlReader.Create(xmlpath, settings);
            while (reader.Read()) { }
        }

        static void settingsValidationEventHandler(object sender, ValidationEventArgs e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
4

0 回答 0