15.11. Validating Modified XML Documents Without Reloading
Problem
You are using the XDocument or the XmlDocument to modify an XML document loaded in memory. Once the document has been modified, the modifications need to be verified, and schema defaults need to be enforced.
Solution
Use the XDocument.Validate method to perform the validation and apply schema defaults and type information.
Create an XmlSchemaSet with the XML Schema document (book.xsd) and an XmlReader and then load the book.xml file using XDocument.Load:
// Create the schema set
XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
// add the new schema with the target namespace
// (could add all the schema at once here if there are multiple)
xmlSchemaSet.Add("http://tempuri.org/Book.xsd",
XmlReader.Create(@"..\..\Book.xsd"));
XDocument book = XDocument.Load(@"..\..\Book.xml");Set up a ValidationEventHandler to catch any errors and then call XDocument.Validate with the schema set and the event handler to validate book.xml against the book.xsd schema:
ValidationHandler validationHandler = new ValidationHandler( ); ValidationEventHandler validationEventHandler = validationHandler.HandleValidation; // validate after load book.Validate(xmlSchemaSet, validationEventHandler);
The ValidationHandler class holds the current validation state in a ValidXml property and the code for the ValidationEventHandler implementation method HandleValidation:
public class ValidationHandler { private object _syncRoot = new object( ); public ValidationHandler( ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access