Reputation: 8576
When querying an XmlDocument I need to pass a namespace manager over with each call. Annoying really but it's just something we live with. The really annoying bit is creating the namespace manager in the first place.
XmlNamespaceManager nsMan = new XmlNamespaceManager(invoiceTextReader.NameTable);
nsMan.AddNamespace("", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2");
nsMan.AddNamespace("pb", "urn:pierbridge:names:specification:pbl:schema:xsd:tpn-1");
...
To create it I need to not only seed the instance with the nametable but then specify every single namespace manually. This seems so silly to me. What's the point in passing the name table if I have to go and add them all manually. And what's the point of passing the name table if I then need to pass the namespace manager back for each and every query. Why can't it just build the namespace manager from what's contained in the document right off the bat. Seems like an awful lot of faffing just to run a query.
Upvotes: 5
Views: 396
Reputation: 100527
NamespaceManager must be passed in if your XPaths have namespace prefixes. Below is list of cases when you don't need namespace manager:
/a/b/c
as XPath*[namespace-uri()='urn:oasis:names' & name()='node1']
.You pass NameTable to allow faster string comparison - same strings are actually the same object if document and namespace manager share the same NameTable. You don't actually have to pass the same NameTable.
You must specify only those prefixes that are used in your XPath. It is often much less than all namespaces in the document. The mapping can't be automatically computed from the XML since prefix to namespace mapping is arbitrary.
This is an example of XML where all prefixes are the same, but map to different namespace each time to show actual need for custom mapping of prefixes in the XPath:
<a:a xmlns='a:my1'>
<a:a xmlns='a:my2' />
<a:a xmlns='a:my3' />
</a>
Upvotes: 3
Reputation: 29654
MSDN states:
Qualifying element and attribute names with a namespace prefix limits the nodes returned by an XPath query to only those nodes that belong to a specific namespace.
For example if the prefix books maps to the namespace http://www.contoso.com/books, then the following XPath query /books:books/books:book selects only those book elements in the namespace http://www.contoso.com/books.
Furthermore:
XPath treats the empty prefix as the null namespace. In other words, only prefixes mapped to namespaces can be used in XPath queries. This means that if you want to query against a namespace in an XML document, even if it is the default namespace, you need to define a prefix for it.
So that should answer your question.
Upvotes: 0