如何根据一个XML节点的属性读取它?

时间:2021-08-07 07:27:53

My XML is built like this:

我的XML是这样构建的:

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

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

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

</Pages>

How can I get the content by ID in C# code?

如何在c#代码中通过ID获取内容?

2 个解决方案

#1


5  

I'd use LINQ to XML and something like:

我将使用LINQ到XML之类的东西:

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

Now page will be the first XElement with the given id, or null if it's not found.

现在page将是第一个具有给定id的XElement,如果没有找到它,则为null。

#2


5  

You could load it into XmlDocument and then call:

你可以把它加载到XmlDocument然后调用:

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

#1


5  

I'd use LINQ to XML and something like:

我将使用LINQ到XML之类的东西:

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

Now page will be the first XElement with the given id, or null if it's not found.

现在page将是第一个具有给定id的XElement,如果没有找到它,则为null。

#2


5  

You could load it into XmlDocument and then call:

你可以把它加载到XmlDocument然后调用:

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