April 20, 2004

Daniel solved in-memory XML validation problem

I like these things. Looks like Daniel solved the famous in-memory XML document validation problem (which I thought is unsolvable!) with XPathNavigatorReader. ...

You can validate against XML Schemas that only define the node where you're standing. The following code validates all expensive books with a narrow schema, instead of a full-blown Pubs schema:
XmlSchema sch = XmlSchema.Read(expensiveBooksSchemaLocation, null);
// Select expensive books.
XPathNodeIterator it = navigator.Select("//titles[price > 10]");
while (it.MoveNext())
{
  // Create a validating reader over an XPathNavigatorReader 
  // for the current node.
  XmlValidatingReader vr = new XmlValidatingReader(
    new XPathNavigatorReader(it.Current));

  // Add the schema for the current node.
  vr.Schemas.Add(sch);

  // Validate it!
  while (vr.Read()) {}
}
This opens the possiblity for modular validation of documents, which is specially useful when you have generic XML processing layers that validate selectively depending on namespaces, for example. What's more, this feature really starts making the XPathDocument/XPathNavigator combination a more feature-complete option to XmlDocument when you only need read-only access to the document.
That's great deal cool. The core problem with XmlValidatingReader is that it requires input to be XmlTextReader and moreover, it calls internal XmlTextReader members. Here is the trick (or hack, whatever): derive from XmlTextReader and cheat the constructor:
public class XPathNavigatorReader : XmlTextReader
{
  public XPathNavigatorReader(XPathNavigator navigator) :
    base(new StringReader(String.Empty))
  ...
And then override XmlTextReader methods (as Daniel did, reading XPathNavigator instead).
What I was thinking about? How could I miss such easy solution? :(

Congrats, Daniel! The best XML.NET hacker hat is yours :)

XPathNavigatorReader is a part of the Mvp.Xml project. I'm going to move the rest of my XML Bestary to the project, test it and then I believe we can step in with the first public release of the Mvp.Xml library, there is enough beef to think about practical usage, not just prototyping.