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

如何用VB.NET 4.0 XmlDocument读取无命名空间XML节点

使用XmlDocument解析无命名空间XML(替代XElement实现)

需求说明

因无法导入Xml.Linq,需将原XElement实现的XML解析逻辑改用VB.NET 4.0的XmlDocument重写,目标是读取XML中的elementCount数值、OPFCategoryCopyBackgroundColor和OPFCategoryCopyName属性值。

原XElement实现逻辑及对应XML结构如下:

原XElement代码

Dim MyXML As XElement = XElement.Load(MemoryStream)
Dim count As Integer = Integer.Parse(MyXML.@elementCount)
For Each MyXElement As XElement In MyXML.Elements
    Dim Components As String() = MyXElement.@OPFCategoryCopyBackgroundColor.Split()
    R = Single.Parse(Components(0).Substring(2))
    G = Single.Parse(Components(1).Substring(2))
    B = Single.Parse(Components(2).Substring(2))
    EName = MyXElement.@OPFCategoryCopyName
Next

对应XML结构

<?xml version="1.0" encoding="utf-8"?>
<categories elementCount="18">
  <category xml:space="preserve" OPFCategoryCopyBackgroundColor="r:0.57 g:0.48 b:0.82" OPFCategoryCopyName="Birthday"></category>
  <category xml:space="preserve" OPFCategoryCopyBackgroundColor="r:0.45 g:0.60 b:0.88" OPFCategoryCopyName="Blue category"></category>
  <category xml:space="preserve" OPFCategoryCopyBackgroundColor="r:0.92 g:0.79 b:0.40" OPFCategoryCopyName="Brown Category"></category>
  <category xml:space="preserve" OPFCategoryCopyBackgroundColor="r:0.63 g:0.26 b:0.80" OPFCategoryCopyName="Family"></category>
</categories>

XmlDocument实现代码

以下是完全对应原逻辑的XmlDocument版本实现:

' 初始化XmlDocument实例并加载内存流中的XML内容
Dim xmlDoc As New XmlDocument()
xmlDoc.Load(MemoryStream)

' 获取根节点<categories>
Dim rootNode As XmlNode = xmlDoc.SelectSingleNode("/categories")

' 读取根节点的elementCount属性,转换为整数
Dim count As Integer = Integer.Parse(rootNode.Attributes("elementCount").Value)

' 遍历所有<category>子节点
For Each categoryNode As XmlNode In rootNode.SelectNodes("category")
    ' 读取背景颜色属性值
    Dim bgColorValue As String = categoryNode.Attributes("OPFCategoryCopyBackgroundColor").Value
    ' 拆分颜色分量,提取RGB数值
    Dim colorComponents As String() = bgColorValue.Split()
    Dim R As Single = Single.Parse(colorComponents(0).Substring(2))
    Dim G As Single = Single.Parse(colorComponents(1).Substring(2))
    Dim B As Single = Single.Parse(colorComponents(2).Substring(2))
    
    ' 读取分类名称属性值
    Dim EName As String = categoryNode.Attributes("OPFCategoryCopyName").Value
    
    ' 此处可添加自定义业务逻辑,比如使用获取到的RGB值和分类名称
Next

关键说明

  • 使用XmlDocument.Load(MemoryStream)加载XML内容,和原XElement.Load逻辑一致;
  • 通过XmlNode.Attributes("属性名").Value获取节点属性值,替代XElement的@属性名语法;
  • 用SelectSingleNode("/categories")定位根节点,SelectNodes("category")获取所有子节点,对应原MyXML.Elements的遍历逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 06:11:13