I'm trying to read the data from an XML file, validating it against the XSD it suggests, into a single data structure (such as XmlDocument). I have a solution, but it requires 2 passes through the file, and I'm wondering if there's a single-pass solution.
MyBooks.xml:
<Books xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:noNamespaceSchemaLocation='books.xsd' id='999'>
<Book>Book A</Book>
<Book>Book B</Book>
</Books>
Books.xsd:
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'
elementFormDefault='qualified'
attributeFormDefault='unqualified'>
<xs:element name='Books'>
<xs:complexType>
<xs:sequence>
<xs:element name='Book' type='xs:string' />
</xs:sequence>
<xs:attribute name='id' type='xs:unsignedShort' use='required' />
</xs:complexType>
</xs:element>
</xs:schema>
Let's say MyBooks.xml and Books.xsd are in the same directory.
Validate:
//Given a filename pointing to the XML file
var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.CloseInput = true;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCB);
//eg:
//private static void ValidationCB(object sender, ValidationEventArgs args)
//{ throw new ApplicationException(args.Message); }
using(var reader = XmlReader.Create(filename, settings))
{ while(reader.Read()) ; }
Read into XmlDocument:
XmlDocument x = new XmlDocument();
x.Load(filename);
Sure, I could collect the nodes as the read from the XmlReader is taking place, but I'd rather not have to do it myself, if possible. Any suggestion?
Thanks in advance