tags:

views:

990

answers:

3

What is the easiest/simplest/cleanest way to:

  1. Read an xml file from the filesystem
  2. Validate the xml against an xsd
  3. Read parts of the xml file into variables

Using .net.

+1  A: 

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.

Miyagi Coder
+4  A: 

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.

Bevan
I think this is what I was looking for. Thank you!
metanaito
+5  A: 

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

marc_s
Thank you. This is also part of what I was looking for. I wish I could mark two answers as solutions.
metanaito