What is the easiest/simplest/cleanest way to:
- Read an xml file from the filesystem
- Validate the xml against an xsd
- Read parts of the xml file into variables
Using .net.
What is the easiest/simplest/cleanest way to:
Using .net.
Use the XMLDocument and XMLNode objects.
You can use the Load and LoadXML methods in XMLDocument to load a xml document. Then you can use the SelectSingleNode to get a value based on the XPath of that node. Or you can use the SelectNodes method to load in an entire node.
You can use the Validate method of the XMLDocument object to validate the XML up against a XSD.
Depending on the level of tolerance and error reporting you want to have, you might find the new XML Api introduced in .NET 3.5 to be useful - the classes XDocument, XElement, XAttribute and so on, all from the System.Xml.Linq namespace.
The design of new XML Api was heavily influenced by lessons learned from the older XMLDocument design, and is much more lightweight and easier to use.
Basically, to get a XSD validation going, you'll need to use a XmlReader with ReaderSettings that define what XSD file to validate against, and events to respond / catch validation errors.
To read the XSD file, use something like this:
StreamReader xsdReader = new StreamReader(xsdFileName);
XmlSchema Schema = new XmlSchema();
Schema = XmlSchema.Read(xsdReader, new ValidationEventHandler(XSDValidationEventHandler));
and the event handler to catch any errors that might show up while reading the XSD (e.g. if it in itself is invalid) would have this signature:
private static void XSDValidationEventHandler(object sender, ValidationEventArgs e)
The error message is in e.Message.
Once you have the XSD loaded in memory, instantiate your XmlReader and use the proper settings to enforce XSD validation:
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.ValidationType = ValidationType.Schema;
ReaderSettings.Schemas.Add(Schema);
ReaderSettings.ValidationEventHandler += new ValidationEventHandler(XMLValidationEventHandler);
This error event handler has the same signature as the one above.
Then actually read the file from beginning to end:
XmlTextReader xmlReader = new XmlTextReader(xmlFileName);
XmlReader objXmlReader = XmlReader.Create(xmlReader, ReaderSettings);
while (objXmlReader.Read()) { }
If any validation errors occured, your event handler was called, and you can capture the error messages in there and e.g. display them to the user (or just have a flag indicating whether validation was successful or not - your call :) )
Marc