Search code examples
asp.netxmlvb.netxpathnavigator

return single attributed value via xpath


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?


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()