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( ...
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.