XPath queries without namespace: XSE to the rescue
Dare has posted about issues with XPath and namespaces in documents. I’m by no means encouraging this, but if you don’t care about namespaces, here’s a solution for you.
Using the XSE reader I proposed (and will upload real soon see the release post), you can setup a handler to catch all elements and remove any namespaces whatsoever, at reading time (i.e. long before the document is loaded), as follows:
public class MyLoader { public XPathDocument Load(string uri) { TransformingXseReader xr = new TransformingXseReader(new XmlTextReader(uri)); XmlNamespaceManager mgr = new XmlNamespaceManager(xr.NameTable); xr.AddHandler(new RelativePath().Create(“*”, mgr), new EventHandler(OnElement)); XPathDocument doc = new XPathDocument(xr); return doc; } private void OnElement(object sender, EventArgs e) { TransformingXseReader tr = (TransformingXseReader) sender; tr.ChangeName(tr.LocalName, String.Empty); } }
The Whidbey version looks more compact:
public class MyLoader { public XPathDocument Load(string uri) { TransformingXseReader xr = new TransformingXseReader(new XmlTextReader(uri)); XmlNamespaceManager mgr = new XmlNamespaceManager(xr.NameTable); xr.AddHandler(new RelativePath().Create(“*”, mgr), delegate { xr.ChangeName(xr.LocalName, String.Empty); } XPathDocument doc = new XPathDocument(xr); return doc; } }
What you effectively get loaded is an infoset without element namespaces, therefore your XPath queries don’t need to care about them anymore.
Update: read these follow-up:
/kzu
/kzu dev↻d