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

使用VB读取XML指定元素值失败求助(目标值:a126be064a25ce3f)

VB.NET 使用XmlDocument读取XML属性值时返回空的问题

问题描述

你尝试从以下XML中获取GroupInfo.Guid的Value属性值(即字符串a126be064a25ce3f):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document Version="7.700000" VersionSeemage="7.7.0.101">
  <Server Type="CLitServerModifiable">
    <CLitInfo>
      <Neutral>
        <GroupInfoPropSet>
          <GroupInfo.List/>
          <GroupInfo.Guid Value="a126be064a25ce3f"/>
        </GroupInfoPropSet>
      </Neutral>
    </CLitInfo>
  </Server>
</Document>

作为VB新手,你写了以下代码,但返回空值:

Dim doc As XmlDocument = New XmlDocument()
doc.Load("test.xml")
Dim str As String = doc.SelectSingleNode("DocumentSmg/Server[Type='CLitServerModifiable']/CLitBOMInfo/Neutral/GroupInfoPropSet/GroupInfo.List/GroupInfo.Guid").InnerText
MsgBox(str)

问题分析

你的代码有两个关键错误导致返回空值:

  • 节点路径错误:
    1. 根节点是<Document>而非DocumentSmg
    2. 节点是<CLitInfo>而非CLitBOMInfo
    3. GroupInfo.Guid直接在GroupInfoPropSet下,不需要经过GroupInfo.List
  • 内容获取方式错误:
    你要的a126be064a25ce3f是GroupInfo.Guid节点的Value属性值,而非节点的文本内容(InnerText),该节点本身没有文本内容,所以InnerText会返回空。

修正后的代码

Dim doc As XmlDocument = New XmlDocument()
doc.Load("test.xml")
' 修正节点路径,并获取Value属性
Dim guidNode As XmlNode = doc.SelectSingleNode("Document/Server[@Type='CLitServerModifiable']/CLitInfo/Neutral/GroupInfoPropSet/GroupInfo.Guid")
If guidNode IsNot Nothing Then
    Dim str As String = guidNode.Attributes("Value").Value
    MsgBox(str)
Else
    MsgBox("未找到目标节点")
End If

补充说明

  • 使用@Type来匹配节点的属性,这是XPath的标准语法
  • 增加了节点是否存在的判断,避免空引用异常
  • 如果习惯使用更简洁的LINQ to XML方式,也可以这样写:
Dim xDoc As XDocument = XDocument.Load("test.xml")
Dim guidValue As String = xDoc.Descendants("GroupInfo.Guid").FirstOrDefault()?.Attribute("Value")?.Value
If guidValue IsNot Nothing Then
    MsgBox(guidValue)
End If

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:04:07