You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CreateNavigator获取XML中指定属性的TransportID值

解决方案:获取指定属性的TransportID值

给定XML片段

<Transport>
    <TransportID TransportIdentifierType="Registration">ABC123A</TransportID>
    <TransportID TransportIdentifierType="Driver">Smith</TransportID>
    <TransportID TransportIdentifierType="Trailer">TR1029</TransportID>
</Transport>

方法1:使用XPath精准定位(推荐)

你之前的XPath路径缺少目标节点名称,修正后可直接通过SelectSingleNode定位到目标节点,完全不依赖节点顺序:

' 假设nav已定位到<Transport>节点
Dim targetNode = nav.SelectSingleNode("TransportID[@TransportIdentifierType='Registration']")
If targetNode IsNot Nothing Then
    Console.WriteLine(targetNode.Value) ' 输出:ABC123A
End If

XPath规则说明:

  • TransportID:指定要查找的子节点名称
  • [@TransportIdentifierType='Registration']:筛选出带有该属性且值为Registration的节点

方法2:遍历节点结合GetAttribute判断

如果偏好遍历方式,可通过GetAttribute直接读取属性值,再做条件筛选:

' 假设nav已定位到<Transport>节点
If nav.MoveToFirstChild() Then
    Do
        If nav.Name = "TransportID" Then
            ' 获取属性值,第二个参数为空表示使用默认命名空间
            Dim attrValue = nav.GetAttribute("TransportIdentifierType", "")
            If attrValue = "Registration" Then
                Console.WriteLine(nav.Value) ' 输出:ABC123A
                Exit Do ' 找到目标后可直接退出循环
            End If
        End If
    Loop While nav.MoveToNext()
    ' 遍历结束后回到<Transport>节点
    nav.MoveToParent()
End If

你之前尝试的问题点

  • 原XPath[@TransportIdentifierType='Registration']缺少节点名称,XPath引擎无法确定筛选对象
  • nav.Value在父节点上返回的是所有子节点文本的拼接结果,无法单独获取属性值,必须通过GetAttribute或定位到目标节点后操作

内容的提问来源于stack exchange,提问作者PutUponDave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 02:31:06