Reputation: 1013
I have a simple xml document below:
<?xml version="1.0" encoding="utf-8"?>
<Research researchID="RT_a" language="eng" xmlns="http://www.rixml.org/2010/1/RIXML" createDateTime="2012-06-30T01:13:38Z">
<Product productID="RT_a">
<SecurityID idType="ISIN" idValue="US0605051046" />
</Product>
</Research>
I am trying to read an attribute "idValue" with the give XPath string. This does not work unless I remove this part:
xmlns="http://www.rixml.org/2010/1/RIXML"
My code is below:
Dim doc As XPathDocument = New XPathDocument("c:\test\test.xml")
Dim strXPath As String = "/Research[1]/Product[1]/SecurityID[1]"
Dim nav As XPathNavigator = doc.CreateNavigator()
Dim mgr As New XmlNamespaceManager(nav.NameTable)
mgr.AddNamespace("", "http://www.rixml.org/2010/1/RIXML")
Dim XPathNode As XPathNavigator = nav.SelectSingleNode(strXPath, mgr)
If XPathNode IsNot Nothing Then
Console.WriteLine(XPathNode.GetAttribute("idValue", String.Empty))
Else
Console.WriteLine("Nothing found")
End If
The row about adding name space have no effect on result - just did some tests with that. What do I need to do/what am I doing wrong?
Upvotes: 1
Views: 1707
Reputation: 3353
Try the following:
Dim strXPath As String = "/x:Research[1]/x:Product[1]/x:SecurityID[1]/@idValue"
Dim nav As XPathNavigator = doc.CreateNavigator()
Dim mgr As New XmlNamespaceManager(nav.NameTable)
mgr.AddNamespace("x", "http://www.rixml.org/2010/1/RIXML")
nav.Evaluate("string(" + strXPath + ")", mgr)
It should return your ID value, or then an empty string if the attribute is not found.
I think the problem may have been the one listed here, that you must explicitly refer to the namespace (even if it is the default one), so by using "x:" you fix it.
Upvotes: 1