0

I'm trying to validate an XML file using an XSD schema, and I want to make certain that particular attributes are present using XmlReaderSettings and its ValidationEventHandler.

Here's an example of what I'm trying to do. Each element has two attributes, "this" and "that". If one is missing or misspelled, I want to raise an exception. Currently, the ValidationEventHandler only raises an exception if the element name is invalid.

XML file:

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

XSD file:

<?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# Code:

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);
        }
    }
}
ishmael
  • 1,796
  • 3
  • 18
  • 19
  • Check out `xs:anyAttribute` which I believe allows you to specify whether "other" attributes are allowed. – Alexei Levenkov Jun 07 '13 at 21:38
  • I'm afraid that doesn't help me, since that property only allows one to add extra attributes not originally defined in the xsd file. I'm trying to raise an error when an attribute is missing or misnamed. – ishmael Jun 07 '13 at 21:51
  • 2
    The `xs:element` for Address inside Addresses does *not* reference the global `xs:element`. Is that a typo? As the schema is above you've not declared a type for Addresses/Address. – Sven Jun 07 '13 at 23:31
  • Arrgh! That was it! Thanks a lot, Sven! – ishmael Jun 07 '13 at 23:56
  • you should take a look at this post http://stackoverflow.com/questions/9018528/xmlreader-getattribute-doesnt-throw-an-exception – terrybozzio Jun 08 '13 at 00:54

0 Answers0