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

VB.NET解析嵌套标签XML:统计歌曲段落数及获取section属性

VB.NET 解析XML统计歌曲Section信息实现方案

先假设你的歌单XML嵌套结构大致如下(可根据实际结构调整):

<Playlist>
  <Song name="歌曲A">
    <Section name="主歌1" part="Verse"/>
    <Section name="副歌1" part="Chorus"/>
    <Section name="桥段" part="Bridge"/>
  </Song>
  <Song name="歌曲B">
    <Section name="主歌1" part="Verse"/>
    <Section name="副歌1" part="Chorus"/>
  </Song>
</Playlist>

下面提供两种VB.NET常用的实现方式:

方法1:传统DOM解析(XmlDocument)

适合复杂嵌套或需要逐节点操作的场景:

Imports System.Xml

' 加载XML文件(也可用LoadXml加载XML字符串)
Dim xmlDoc As New XmlDocument()
xmlDoc.Load("你的歌单XML文件路径.xml")

' 获取所有歌曲节点
Dim songNodes As XmlNodeList = xmlDoc.SelectNodes("//Song")

' 遍历每首歌统计Section
For Each songNode As XmlNode In songNodes
    Dim songName = songNode.Attributes("name").Value
    ' 提取当前歌曲下的所有Section节点
    Dim sectionNodes = songNode.SelectNodes("Section")
    Dim sectionCount = sectionNodes.Count

    ' 输出统计结果(可替换为存入变量/数据库等逻辑)
    Console.WriteLine($"歌曲:{songName},Section数量:{sectionCount}")

    ' 遍历每个Section获取name和part属性
    For Each sectionNode As XmlNode In sectionNodes
        Dim secName = sectionNode.Attributes("name").Value
        Dim secPart = sectionNode.Attributes("part").Value
        Console.WriteLine($"  - 段落:{secName},类型:{secPart}")
    Next
Next

方法2:LINQ to XML(简洁现代方式)

代码更紧凑,适合结构清晰的XML:

Imports System.Xml.Linq

' 加载XML文档
Dim xDoc As XDocument = XDocument.Load("你的歌单XML文件路径.xml")

' 遍历歌曲节点处理
For Each song In xDoc.Descendants("Song")
    Dim songName = song.Attribute("name").Value
    Dim sections = song.Descendants("Section").ToList()
    Dim sectionCount = sections.Count

    Console.WriteLine($"歌曲:{songName},Section数量:{sectionCount}")

    ' 提取每个Section的属性
    For Each section In sections
        Dim secName = section.Attribute("name").Value
        Dim secPart = section.Attribute("part").Value
        Console.WriteLine($"  - 段落:{secName},类型:{secPart}")
    Next
Next

注意事项

  • 确保代码中节点/属性名称和XML实际内容完全一致,XML是大小写敏感的
  • 如果XML包含命名空间,需要在解析时指定XNamespace(LINQ方式)或在XPath中加入命名空间前缀(XmlDocument方式)
  • 可以自定义实体类(比如SongInfo、SectionInfo)来存储统计结果,方便后续和MIDI灯光控制逻辑对接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 12:25:11