如何使用XML Schema验证属性名称?

时间:2013-06-07 21:23:13

标签: c# xml

我正在尝试使用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);
        }
    }
}

0 个答案:

没有答案