XML (.NET 1.1) Performance Guidelines - Validating XML

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Srinath Vasireddy, Ashish Babbar, and Alex Mackman



Use XmlValidatingReader

A lot of specialized code is required to validate an XML document to ensure that the document matches the rules defined in a schema or a DTD. By using XmlValidatingReader, you avoid writing this code by hand. It also means that after validation, your application can make assumptions about the condition of the data. Permitting your application to make assumptions about the data can reduce the quantity of error-handling code that you would otherwise have to write.


Do Not Validate the Same Document More Than Once

Make sure that you do not waste processor cycles by validating the same source document multiple times.


Consider Caching the Schema

If you repeatedly validate input XML against the same schema on a per-request basis, consider loading the schema once and retaining it in memory for later requests. This avoids the overhead of parsing, loading, and compiling the schema multiple times. The following code fragment shows how to cache a schema in an XmlSchemaCollection object.


  XmlTextReader tr = new XmlTextReader("Books.xml");
  XmlValidatingReader vr = new XmlValidatingReader(tr);
  XmlSchemaCollection xsc = new XmlSchemaCollection();
  xsc.Add("urn:bookstore-schema", "Books.xsd");
  vr.Schemas.Add(xsc);

Validation comes at a cost. Typically, using the XmlValidatingReader to validate a document is two to three times slower than using the XmlTextReader to simply parse the XML, so ensure that this is worth the cost in your particular application scenario.


References

For more information about XML validation, see Microsoft Knowledge Base article 307379, "HOW TO: Validate an XML Document by Using DTD, XDR, or XSD in Visual C# .NET," at http://support.microsoft.com/default.aspx?scid=kb;en-us;307379.

Personal tools