Cottleston Pie

Fernando Felman’s thoughts on software development

  • Categories Navigation

  • Topics

  • Archives

  • Advertisements

Archive for the ‘XML’ Category

Using XPath with Namespaces

Posted by Fernando Felman on April 9, 2007

This is something I’ve been asked about quite a lot: how to perform XPath queries with namespaces. I will demonstrate how to do that using a sample InfoPath form XML file. InfoPath generates the schema for the XML form at design time and the URI for the schema contains the Date & Time the schema was created, so it’s a dynamically generated URI.

Here’s a sample of an InfoPath file. Notice the URI of the ‘my’ prefix and how it contains the Date & Time of when the structure was created
InfoPath Sample Form

We’ll fetch the generated namespace URI at runtime and use that namespace to perform an XPath query.
The generated namespace in InfoPath will always have the ‘my’ prefix and will always be declared in the root node. With that piece of knowledge in mind Knowing that it’s easy to fetch the generated URI using the GetNamespaceOfPrefix method:
Fetch URI from Xml Node

We can now load the generated namespace URI into an XmlNamepsaceManager class. With the namespace loaded we can perform an XPath namespace-aware query to fetch the ‘destination’ node. Notice that I chose to use the ‘infoPath’ prefix instead of the ‘my’ prefix to emphasize the fact that the prefix used in the XML file (i.e. ‘my’) has no meaning in the XPath query:
XPath query with namesapce

To conclude: in order to use XPath queries with namespaces you must first load the namespace into an XmlNamesapceManager. You can then use the prefix of the namespace to perform an XPath query using the namespace manager. You can also fetch namespaces from a node using either its URI or its prefix.


Posted in .Net v2, Samples, XML | 2 Comments »