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

如何用XPath筛选同时含指定type的address_component的long_name

VB.NET解决XML获取long_name时的空引用错误

问题原因

空引用错误本质是访问了未实例化的对象,常见场景:

  • 你认为找到的address_component元素实际不存在(筛选逻辑有漏洞)
  • 符合条件的address_component里没有long_name子元素
  • 直接访问节点属性/值时未先判断节点是否为null

解决方案:逐层检查节点存在性 + 准确筛选元素

以下提供两种常用实现方式,均包含空值检查,彻底避免空引用。

方式1:LINQ to XML(推荐,语法更简洁)

先假设你的XML结构类似:

<root>
  <address_component>
    <long_name>Vleuten-De Meern</long_name>
    <type>sublocality</type>
    <type>sublocality_level_1</type>
  </address_component>
  <address_component>
    <long_name>Utrecht</long_name>
    <type>locality</type>
  </address_component>
</root>

对应的VB.NET代码:

Imports System.Xml.Linq

' 加载XML(文件或字符串)
Dim xmlDoc As XDocument = XDocument.Load("你的XML文件路径.xml")
' 若用字符串加载则替换为:XDocument.Parse("你的XML字符串内容")

' 筛选同时包含两个指定type值的address_component
Dim targetComponent = xmlDoc.Descendants("address_component").FirstOrDefault(Function(ac)
    Dim typeList = ac.Descendants("type").Select(Function(t) t.Value).ToList()
    Return typeList.Contains("sublocality") AndAlso typeList.Contains("sublocality_level_1")
End Function)

' 安全获取long_name
If targetComponent IsNot Nothing Then
    Dim longNameElement = targetComponent.Element("long_name")
    If longNameElement IsNot Nothing Then
        Dim result = longNameElement.Value
        ' 这里处理获取到的long_name,比如输出或赋值
        Console.WriteLine(result)
    Else
        Console.WriteLine("该address_component下不存在long_name元素")
    End If
Else
    Console.WriteLine("未找到符合条件的address_component")
End If

方式2:XmlDocument + XPath

Imports System.Xml

Dim xmlDoc As New XmlDocument()
xmlDoc.Load("你的XML文件路径.xml")

' XPath表达式精准筛选目标元素
Dim xpath As String = "//address_component[type='sublocality' and type='sublocality_level_1']"
Dim targetComponent As XmlNode = xmlDoc.SelectSingleNode(xpath)

If targetComponent IsNot Nothing Then
    Dim longNameNode As XmlNode = targetComponent.SelectSingleNode("long_name")
    If longNameNode IsNot Nothing Then
        Console.WriteLine(longNameNode.InnerText)
    Else
        Console.WriteLine("缺失long_name节点")
    End If
Else
    Console.WriteLine("无匹配的address_component")
End If

关键注意点

  • 用FirstOrDefault(LINQ)或SelectSingleNode(XPath)替代直接取第一个元素,避免找不到元素时抛出异常
  • 对每一层节点(address_component、long_name)都做IsNot Nothing检查,确保存在后再访问值
  • 筛选type时,要确保当前address_component下同时包含两个目标type值,避免漏判或误判

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:39:20