分析 XML 和提取节点

本文关键字:节点 提取 XML 分析 | 更新日期: 2023-09-27 18:35:03

我有以下XML:

<bookstore>
    <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
            <first-name>Benjamin</first-name>
            <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
    </book>
</bookstore>

我想阅读它并显示如下结果:

Genre: autobiography
Publication: 1981-03-22
ISBN: 1-861003-11-0
Title: The Autobiography of Benjamin Franklin
Author: Benjamin Franklin
Price: 8.99

分析 XML 和提取节点

这里有一些示例代码来使用 XElement 执行此操作:

    var xml = XElement.Load("test.xml");
    foreach (var bookEl in xml.Elements("book"))
    {
        Console.WriteLine("Genre: " + bookEl.Attribute("genre").Value
            + " " + "Publication: " + bookEl.Attribute("publicationdate").Value
            + " " + "ISBN: " + bookEl.Attribute("ISBN").Value);
        Console.WriteLine("Title: " + bookEl.Element("title").Value);
        Console.WriteLine("Author: " + bookEl.Element("author").Element("first-name").Value 
            + " " + bookEl.Element("author").Element("last-name").Value);
        Console.WriteLine("Price: " + bookEl.Element("price").Value);
    }