Get Last Element in C# using XElement

2019-02-27 07:07发布

I have a XML feed loaded in an XElement.

The structure is

<root>
<post></post>
<post></post>
<post></post>
<post></post>
.
.
.
.
<post></post>
</root>

I want to directly get the value of the Last post. How I do that using XElement in C#.

Thanks.

标签: c# xml xelement
5条回答
唯我独甜
2楼-- · 2019-02-27 07:39

Try this:

rootElement.Descendants().Last()

If you aren't sure there'll be any, you could also use LastOrDefault(). If there might be other elements besides within the , there's an overload of Descendants that will let you find just the posts you're looking for.

查看更多
一纸荒年 Trace。
3楼-- · 2019-02-27 07:43

Try this

XDocument doc= XDocument.Load("path to xml");
var last=doc.Root.LastNode;
查看更多
叼着烟拽天下
4楼-- · 2019-02-27 08:02

Or try this to get XElement:

XDocument doc = XDocument.Load("yourfile.xml");          
XElement root = doc.Root;
Console.WriteLine(root.Elements("post").Last());
查看更多
看我几分像从前
5楼-- · 2019-02-27 08:02

You can use LastNode property on root element:

XElement root = doc.Root;
XElement lastPost = (XElement)root.LastNode;
查看更多
戒情不戒烟
6楼-- · 2019-02-27 08:06
var doc = XDocument.Parse(xml);
var lastPost = doc.Descendants("post").Last();
查看更多
登录 后发表回答