Question

I've got some XML

<?xml version="1.0" encoding="utf-8"?>
<rsp stat="ok">
  <auth>
    <token>123456</token>
    <perms>write</perms>
    <user nsid="74461753@N03" username="user" fullname="name" />
  </auth>
</rsp>

And I'm trying to use XPath to get the value of "token" into a string. Simple huh. But can I do it?

Dim doc As New XmlDocument
doc.Load(url)   'gets the XML above.

Dim xmlNav As XPathNavigator

Dim xmlNI As XPathNodeIterator

xmlNav = doc.CreateNavigator()

xmlNI = xmlNav.Select("token")

How to I output the "123456" into a variable?

Was it helpful?

Solution

XPathNodeIterator Class provides a set of selected nodes that you can iterate over. There are two problems with your code.

First, your XPath is incorrect - it should be "/rsp/auth/token", not "token".

Secondly, you need to iterate over the collection returned (in this case you're only getting one node). You can do this one of two ways:

xmlNI = xmlNav.Select("/rsp/auth/token")
xmlNI.MoveNext()
Dim selectedNode As XPathNavigator = xmlNI.Current
' value of the node can be accessed by selectedNode.Value

Or you can use a For Each loop:

For Each node As XPathNavigator In xmlNI
    ' value of the node can be accessed by node.Value
Next

If you can use LINQ to XML, this is even simpler (you'll need to add a reference to System.Xml.Linq via Imports System.Xml.Linq):

Dim xml As XElement = XElement.Load(url)

Dim auth As String = xml.Descendants("token").FirstOrDefault()

OTHER TIPS

Do you need XPathNavigator necessarily? I got it like this:

Dim list As Xml.XmlNodeList = doc.SelectNodes("rsp/auth/token")
If list IsNot Nothing And list.Count > 0 Then
    Dim myValue As String = list(0).FirstChild.Value
    Console.WriteLine(myValue) 'prints 123456'
End If

The XmlDocument contains methods to get Elements per XPath.

Dim doc As New XmlDocument
doc.Load(url)

Dim TokenElement As XmlElement = doc.DocumentElement.SelectSingleNode("auth/token/text()")

If(Not(TokenElement Is Nothing)) Then 'XmlNode.SelectSingleNode(String) can be Nothing if the expression finds no node
    Dim strValue As String = TokenElement.Value
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top