繁体   English   中英

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

[英]Get Last Element in C# using XElement

我在XElement中加载了XML Feed。

结构是

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

我想直接获取Last帖子的值。 我如何在C#中使用XElement。

谢谢。

或者尝试这个来获得XElement:

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

您可以在根元素上使用LastNode属性:

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

尝试这个:

rootElement.Descendants().Last()

如果你不确定会有什么,你也可以使用LastOrDefault()。 如果除了内部可能还有其他元素,那么Descendants的重载会让您找到您正在寻找的帖子。

尝试这个

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