Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用XElement获取C#中的最后一个元素_C#_Xml_Xelement - Fatal编程技术网

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

使用XElement获取C#中的最后一个元素,c#,xml,xelement,C#,Xml,Xelement,我在XElement中加载了一个XML提要 结构是 <root> <post></post> <post></post> <post></post> <post></post> . . . . <post></post> </root> . . . . 我想直接得到最后一篇文章的价值。如何使用C#中的XElement实现这一点 谢谢。您可以对根元素

我在XElement中加载了一个XML提要

结构是

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

.
.
.
.
我想直接得到最后一篇文章的价值。如何使用C#中的XElement实现这一点


谢谢。

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

XElement root = doc.Root;
XElement lastPost = (XElement)root.LastNode;
试试这个:

rootElement.Descendants().Last()
如果不确定是否会有,也可以使用LastOrDefault()。如果在中可能还有其他元素,则子体会过多,这样您就可以找到您正在查找的帖子。

试试这个

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

或者尝试以下操作以获得XElement:

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