简体   繁体   English

使用XElement在C#中获取最后一个元素

[英]Get Last Element in C# using XElement

I have a XML feed loaded in an XElement. 我在XElement中加载了XML Feed。

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. 我想直接获取Last帖子的值。 How I do that using XElement in C#. 我如何在C#中使用XElement。

Thanks. 谢谢。

Or try this to get XElement: 或者尝试这个来获得XElement:

XDocument doc = XDocument.Load("yourfile.xml");          
XElement root = doc.Root;
Console.WriteLine(root.Elements("post").Last());

You can use LastNode property on root element: 您可以在根元素上使用LastNode属性:

XElement root = doc.Root;
XElement lastPost = (XElement)root.LastNode;
var doc = XDocument.Parse(xml);
var lastPost = doc.Descendants("post").Last();

Try this: 尝试这个:

rootElement.Descendants().Last()

If you aren't sure there'll be any, you could also use LastOrDefault(). 如果你不确定会有什么,你也可以使用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. 如果除了内部可能还有其他元素,那么Descendants的重载会让您找到您正在寻找的帖子。

Try this 尝试这个

XDocument doc= XDocument.Load("path to xml");
var last=doc.Root.LastNode;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM