Sunday, April 6, 2008

XPathNavigator and default namespaces

Here is a sample xml document with a default namespace:

<?xml version="1.0" encoding="utf-16"?>
<Invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://informationage.co.nz/schema/invoicing">
<Amount>1906.50</AmountExcGst>
</Invoice>


How do I read the amount node in this xml document.



XmlDocument lXmlDoc = new XmlDocument();
lXmlDoc.LoadXml( soome source for the document above );

// Namespaces
XmlNamespaceManager lNamespaceManager = new XmlNamespaceManager( new NameTable( ) );
// Arbitrary prefix used for default namespace
lNamespaceManager.AddNamespace( "d", "http://informationage.co.nz/schema/invoicing" );

// Navigator
XPathNavigator lNavigator = lXmlDoc.CreateNavigator();
// Note that the default namespace elements must be preifxed with the namespace prefix.
XPathNavigator lNodeNav = lNavigator.SelectSingleNode( "/d:Invoice/d:Amount", lNamespaceManager );



The important thing to note here is that the XPath expression elements MUST be prefixed with the default namespace prefix
added to the namespace manager.

The expression "/Invoice/Amount" will return null.

This one wasted quite a bit of my time so I hope this helps someone else.

Andy

No comments: