如何使用C#中的XmlDocument获取特定节点的内容

本文关键字:节点 获取 何使用 中的 XmlDocument | 更新日期: 2023-09-27 18:27:30

我有一个XML文件,看起来像:

<root>
    <song id="1">
        <name> A Whole New World </name>
        <artist> Lea Salonga </artist>
    </song>
    <song id="2">
        <name> Colors of the Wind </name>
        <artist> Judy Kuhn </artist>
    </song>
    <song id="3">
        <name> Reflection </name>
        <artist> Lea Salonga </artist>
    </song>
    <song id="4">
        <name> Part of Your World </name>
        <artist> Sierra Boggess </artist>
    </song>
</root>

我想用C#解析这个XML文件。我知道应该使用System.Xml.XmlDocument来解析XML文件。微软文档称,方括号运算符[Name]只返回"具有指定Name的第一个子元素"。

所以我的问题是:如何从上面的示例XML文件中获得id为4的歌曲的名称

如何使用C#中的XmlDocument获取特定节点的内容

查看Xpath并使用Xpath查询,可以在此处进行测试http://www.xpathtester.com/test

//song[@id="4"]/name

在c#escape"字符与''类似

"//song[@id='"4'"]/name"

如果您不想使用Xpath查询,可以使用旧方法:

您可以在子节点上循环,检查每个子元素的名称是否为"song",然后检查属性,然后获取名称。但Xpath会更短。