【发布时间】:2011-10-25 04:44:28
【问题描述】:
我在 XElement 中加载了一个 XML 提要。
结构是
<root>
<post></post>
<post></post>
<post></post>
<post></post>
.
.
.
.
<post></post>
</root>
我想直接获取 Last post 的值。我如何在 C# 中使用 XElement。
谢谢。
【问题讨论】:
我在 XElement 中加载了一个 XML 提要。
结构是
<root>
<post></post>
<post></post>
<post></post>
<post></post>
.
.
.
.
<post></post>
</root>
我想直接获取 Last post 的值。我如何在 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;
【讨论】: