簡體   English   中英

如何通過屬性讀取單個XML節點?

[英]How can I read a single XML node by it's attribute?

我的XML是這樣構建的:

<?xml version="1.0" encoding="utf-8" ?>
<Pages>

    <Page id="1" title="myTitle">
        Content
    </Page>

    <Page id="2" title="myTitle2">
        Content2
    </Page>

</Pages>

如何通過C#代碼中的ID獲取內容?

您可以將其加載到XmlDocument中,然后調用:

xmldocument.SelectSingleNode("/Pages/Page[Id = '1']")

我將使用LINQ to XML之類的東西:

var document = XDocument.Load(...);
var page = document.Descendants("Page")
                   .Where(x => (int) x.Attribute("id") == id)
                   .FirstOrDefault();

現在page將是第一個具有給定id XElement ;如果找不到,則為null。

暫無
暫無

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

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