Easiest way to check and read xml file in .net?

What is the easiest / easiest / cleanest way:

  • Read the xml file from the file system
  • Check xml on xsd
  • Reading parts of xml file in variables

Using .net.

+6
xml xsd
source share
3 answers

Depending on the tolerance level and error reporting you want, you may find the new Api XML embedded in .NET 3.5 useful: the XDocument , XElement , XAttribute , etc. classes, all from the System.Xml namespace. Linq .

The development of the new Api XML was greatly influenced by the lessons learned from the earlier XMLDocument design, and much easier and easier to use.

+6
source share

Basically, in order to get an XSD check, you will need to use XmlReader with ReaderSettings, which determine which XSD file to check and the events should respond to check / catch 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 will catch any errors that may appear when reading the XSD (for example, if it is itself invalid) would have the following signature:

 private static void XSDValidationEventHandler(object sender, ValidationEventArgs e) 

The error message is in the e.Message file.

Once you have XSD loaded into memory, create an XmlReader instance and use the correct settings to provide 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 above.

Then actually read the file from start to finish:

 XmlTextReader xmlReader = new XmlTextReader(xmlFileName); XmlReader objXmlReader = XmlReader.Create(xmlReader, ReaderSettings); while (objXmlReader.Read()) { } 

If any validation errors occur, an event handler is called, and you can write error messages there, etc. display them to the user (or just have a flag indicating whether the check was successful or not - your call :))

+10
source share

Use the XMLDocument and XMLNode objects.

You can use the Load and LoadXML methods in an XMLDocument to load an XML document. Then you can use SelectSingleNode to get the XPath value of this node. Or you can use the SelectNodes method to load the entire node.

You can use the Validate method of an XMLDocument object to validate XML on an XSD.

+2
source share

All Articles