Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Xpath With Default Namespace in C#

I've got an XML document with a default namespace. I'm using a XPathNavigator to select a set of nodes using Xpath as follows:

XmlElement myXML = ...;   XPathNavigator navigator = myXML.CreateNavigator(); XPathNodeIterator result = navigator.Select("/outerelement/innerelement"); 

I am not getting any results back: I'm assuming this is because I am not specifying the namespace. How can I include the namespace in my select?

like image 468
macleojw Avatar asked Feb 25 '09 12:02

macleojw


People also ask

What is XPath default namespace?

The Default NamespaceXPath 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.

What is local name () in XPath?

The local-name function returns a string representing the local name of the first node in a given node-set.

What is XML namespace with example?

An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name.


1 Answers

First - you don't need a navigator; SelectNodes / SelectSingleNode should suffice.

You may, however, need a namespace-manager - for example:

XmlElement el = ...; //TODO XmlNamespaceManager nsmgr = new XmlNamespaceManager(     el.OwnerDocument.NameTable); nsmgr.AddNamespace("x", el.OwnerDocument.DocumentElement.NamespaceURI); var nodes = el.SelectNodes(@"/x:outerelement/x:innerelement", nsmgr); 
like image 162
Marc Gravell Avatar answered Oct 07 '22 00:10

Marc Gravell