15.4. Validating XML
Problem
You are accepting an XML document created by another source, and you want to verify that it conforms to a specific schema. This schema may be in the form of an XML schema (XSD or XML—XDR); alternatively, you want the flexibility to use a document type definition (DTD) to validate the XML.
Solution
Use the XDocument.Validate
method and XmlReader.Settings
property to validate XML documents against any descriptor document, such as an XSD, a DTD, or an XDR, as shown in Recipe 15.4.
Example 15-4. Validating XML
public static void ValidateXml() { // open the bookbad.xml file XDocument book = XDocument.Load(@"..\..\BookBad.xml"); // create XSD schema collection with book.xsd XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null,@"..\..\Book.xsd"); // wire up handler to get any validation errors book.Validate(schemas, settings_ValidationEventHandler); // create a reader to roll over the file so validation fires XmlReader reader = book.CreateReader(); // report warnings as well as errors reader.Settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; // use XML Schema reader.Settings.ValidationType = ValidationType.Schema; // roll over the XML while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { Console.Write("<{0}", reader.Name); while (reader.MoveToNextAttribute()) { Console.Write(" {0}='{1}'", reader.Name, reader.Value); } Console.Write(">"); } else if (reader.NodeType == XmlNodeType.Text) { Console.Write(reader.Value); ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.