【问题标题】:return single attributed value via xpath通过 xpath 返回单个属性值
【发布时间】:2013-04-19 13:50:13
【问题描述】:

我有一些 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>

我正在尝试使用 XPath 将“token”的值转换为字符串。简单吧。但我能做到吗?

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

如何将“123456”输出到变量中?

【问题讨论】:

标签: asp.net xml vb.net xpathnavigator


【解决方案1】:

XPathNodeIterator Class 提供了一组可以迭代的选定节点。您的代码有两个问题。

首先,您的 XPath 不正确 - 它应该是“/rsp/auth/token”,而不是“token”。

其次,您需要遍历返回的集合(在这种情况下,您只会得到一个节点)。您可以通过以下两种方式之一执行此操作:

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

或者您可以使用 For Each 循环:

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

如果您可以使用 LINQ to XML,那就更简单了(您需要通过 Imports System.Xml.Linq 添加对 System.Xml.Linq 的引用):

Dim xml As XElement = XElement.Load(url)

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

【讨论】:

    【解决方案2】:

    您一定需要XPathNavigator 吗?我是这样理解的:

    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
    

    【讨论】:

    • 漂亮、简单、真实。但我得到“类型'Xml.XmlNodeList'未定义。”
    【解决方案3】:

    XmlDocument 包含获取每个 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
    

    【讨论】:

    • 这看起来很有希望,但它并没有成功。 auth/token/text() 是正确的表示法吗?
    • 使用doc.DocumentElement,您将获得根标签&lt;rsp /&gt;。因此,您将获得具有给定符号的 &lt;token /&gt; 值。是否也可以使用doc.SelectSingleNode("rsp/auth/token/text()") 来获得相同的结果。我更喜欢第一种表示法,因为我不知道根标签的名称。
    • 我的回答只给了你&lt;token /&gt;标签的第一次出现。如果您想在此结构中包含所有标签,您可以使用For Each NodeValue As String In doc.DocumentElement.SelectNodes("auth/token/text()") 'do something with the value Next 遍历所有找到的&lt;token /&gt; 值。
    猜你喜欢
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2011-06-17
    • 2012-02-10
    • 1970-01-01
    相关资源
    最近更新 更多