簡體   English   中英

使用XpathNavigator在C#中讀取XML文件

[英]Reading XML file in C# with XpathNavigator

我試圖在MSDN網站上閱讀作為示例提供的book.xml文件。

    <?xml version="1.0" encoding="utf-8" ?> 
<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>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
            <first-name>Herman</first-name>
            <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
    </book>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

到目前為止,我有以下代碼:

static void Main()
        {
            XmlDocument document = new XmlDocument();
            document.Load(@"c:\books.xml");

            XPathNavigator navigator = document.CreateNavigator();

            XPathNodeIterator nodes = navigator.Select("/bookstore/book");


            while (nodes.MoveNext())
            {
                Console.WriteLine(nodes.Current.HasAttributes);
            }


        }

似乎這段代碼正在閱讀所有內容,但是從這里開始,如果我想要顯示所有書籍的標題等,我該如何訪問它們?

如果更改XPath表達式以選擇所有標題節點,則可以迭代標題:

XPathDocument document = new XPathDocument(@"c:\tmp\smpl5.xml");
XPathNavigator navigator = document.CreateNavigator();

XPathNodeIterator nodes = navigator.Select("/bookstore/book/title");

foreach (XPathNavigator item in nodes)
{
    Console.WriteLine(item.Value);
}

請注意,如果您不打算修改文檔,則無需創建XmlDocument 使用XPathDocument通常更輕量級。

你也可以使用這個“// title”而不是“/ bookstore / book”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM