如何用VB的XmlReader读取XML中RX节点嵌套的属性值
解决方案
要读取
- 定位到
元素后,通过属性名称获取 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
相关产品推荐
相关产品推荐

