Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath select node with namespace

Its a .vbproj and looks like this

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">     <PropertyGroup>         <ProjectGuid>15a7ee82-9020-4fda-a7fb-85a61664692d</ProjectGuid> 

all i want to get is the ProjectGuid but it does not work when a namespace is there...

 Dim xmlDoc As New XmlDocument()  Dim filePath As String = Path.Combine(mDirectory, name + "\" + name + ".vbproj")  xmlDoc.Load(filePath)  Dim value As Object = xmlDoc.SelectNodes("/Project/PropertyGroup/ProjectGuid") 

what can i do to fix this?

like image 298
Peter Avatar asked Feb 11 '09 11:02

Peter


People also ask

What is namespace node in XPath?

XPath queries are aware of namespaces in an XML document and can use namespace prefixes to qualify element and attribute names. 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.

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 namespace in XML file?

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.


2 Answers

I'd probably be inclined to go with Bartek's* namespace solution, but a general xpath solution is:

//*[local-name()='ProjectGuid']

**since Bartek's answer has disappeared, I recommend Teun's (which is actually more thorough)*

like image 198
annakata Avatar answered Sep 22 '22 19:09

annakata


The best way to do things like this (IMHO) is to create a namespace manager. This can be used calling SelectNodes to indicate which namespace URLs are connected to which prefixes. I normally set up a static property that returns an adequate instance like this (it's C#, you'll have to translate):

private static XmlNamespaceManager _nsMgr; public static XmlNamespaceManager NsMgr {   get   {     if (_nsMgr == null)     {       _nsMgr = new XmlNamespaceManager(new NameTable());       _nsMgr.AddNamespace("msb", "http://schemas.microsoft.com/developer/msbuild/2003");     }     return _nsMgr;   } } 

I include only one namespace here, but you could have multiple. Then you can select from the document like this:

Dim value As Object = xmlDoc.SelectNodes("/msb:Project/msb:PropertyGroup/msb:ProjectGuid", NsMgr) 

Note that all of the elements are in the specified namespace.

like image 40
Teun D Avatar answered Sep 21 '22 19:09

Teun D