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

使用VB.Net与XmlDocument解析XML遇到问题求助

解决VB.Net解析特定XML节点的问题

问题分析

你的代码里有两个核心问题,导致无法同时获取目标属性:

  • XPath路径错误:你用了/response/result/incoming_did_routes/incoming_did_route/*,这会选中incoming_did_route下的所有子节点(比如extension),而不是incoming_did_route本身——这些子节点自然没有number、name、note属性,运行时会报错。
  • 未筛选指定类型节点:没有过滤出type="route_number"的incoming_did_route节点,导致会处理到其他类型的节点(比如default_route),进一步引发异常。

修正后的完整代码

下面是调整后的代码,包含节点筛选、属性获取和空值防护,完美适配你的XML结构:

Dim doc As New XmlDocument()
doc.Load("filename.xml")

' 精准筛选出所有type="route_number"的incoming_did_route节点
Dim routeNodes As XmlNodeList = doc.SelectNodes("/response/result/incoming_did_routes/incoming_did_route[@type='route_number']")

For Each routeNode As XmlNode In routeNodes
    ' 获取incoming_did_route自身的属性,添加空值判断避免异常
    Dim number As String = If(routeNode.Attributes("number") IsNot Nothing, routeNode.Attributes("number").Value, "")
    Dim name As String = If(routeNode.Attributes("name") IsNot Nothing, routeNode.Attributes("name").Value, "")
    Dim note As String = If(routeNode.Attributes("note") IsNot Nothing, routeNode.Attributes("note").Value, "")
    
    ' 从当前路由节点下找到extension子节点,再获取它的account_id属性
    Dim extensionNode As XmlNode = routeNode.SelectSingleNode("extension")
    Dim account_id As String = If(extensionNode IsNot Nothing AndAlso extensionNode.Attributes("account_id") IsNot Nothing, extensionNode.Attributes("account_id").Value, "")
    
    ' 这里可以添加你的业务处理逻辑,比如将数据存入集合或打印
    Console.WriteLine($"Number: {number}, Name: {name}, Note: {note}, Account ID: {account_id}")
Next

代码关键说明

  • 精准XPath筛选:[@type='route_number']是属性筛选条件,确保只处理符合你需求的路由节点,自动忽略其他类型的节点。
  • 空值防护机制:用If判断属性或节点是否存在,避免NullReferenceException——这在XML节点属性可能缺失的场景下非常重要。
  • 层级关系正确:先获取incoming_did_route节点本身,再从它内部查找extension子节点,这样就能分别拿到父节点和子节点的目标属性。

测试结果

用你提供的XML文件测试,这段代码会输出:

Number: 0000, Name: 000-000-0000, Note: jane doe, Account ID: 3333
Number: 0001, Name: 000-000-0001, Note: john doe, Account ID: 3334

完全符合你的需求,不会处理无关的路由节点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:30:08