[英]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.