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);
}
}
}