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

如何用VB的XmlReader读取XML中RX节点嵌套的属性值

解决方案

要读取节点属性中内嵌的XML内容,需按以下步骤处理:

  • 定位到元素后,通过属性名称获取m_rx.astrDemod_value_0的转义XML字符串(不建议用索引,避免属性顺序变化导致读取错误)。
  • 解码转义字符串,将<、"等实体还原为原始XML字符。
  • 用XmlReader解析解码后的内嵌XML,提取的m_freq.n64RX和的m_mode.nMode属性值。

修改后的VB代码

Imports System.Xml
Imports System.IO
Imports System.Net

' 读取主XML文件
Dim xmlToTxt As XmlReader = XmlReader.Create(filename)

Do While xmlToTxt.Read()
    If xmlToTxt.NodeType = XmlNodeType.Element AndAlso xmlToTxt.Name = "RX" Then
        ' 读取m_rx.nActive属性(原需求保留)
        Dim activeValue As String = xmlToTxt.GetAttribute("m_rx.nActive")
        MsgBox("m_rx.nActive: " & activeValue)

        ' 获取内嵌的转义XML字符串
        Dim innerXmlEncoded As String = xmlToTxt.GetAttribute("m_rx.astrDemod_value_0")
        If Not String.IsNullOrEmpty(innerXmlEncoded) Then
            ' 解码XML实体,还原原始XML内容
            Dim innerXmlDecoded As String = WebUtility.HtmlDecode(innerXmlEncoded)

            ' 解析内嵌XML
            Using innerReader As XmlReader = XmlReader.Create(New StringReader(innerXmlDecoded))
                Do While innerReader.Read()
                    If innerReader.NodeType = XmlNodeType.Element Then
                        Select Case innerReader.Name
                            Case "Freq"
                                ' 提取m_freq.n64RX属性
                                Dim rxFreq As String = innerReader.GetAttribute("m_freq.n64RX")
                                MsgBox("m_freq.n64RX: " & rxFreq)
                            Case "Mode"
                                ' 提取m_mode.nMode属性
                                Dim modeValue As String = innerReader.GetAttribute("m_mode.nMode")
                                MsgBox("m_mode.nMode: " & modeValue)
                        End Select
                    End If
                Loop
            End Using
        End If
    End If
Loop

关键说明

  • 使用WebUtility.HtmlDecode解码转义字符:该方法兼容.NET Framework、.NET Core及后续版本,无需额外引用System.Web。
  • 嵌套使用XmlReader:保持内存高效,适合处理大型XML文档。
  • 按名称读取属性:避免依赖属性顺序,提升代码稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:19:53