繁体   English   中英

如何获取特定类型 C#、XML、LINQtoXML 的最后一个 XElement

[英]How to get the last XElement of particular type C#, XML, LINQtoXML

我遇到了以下链接上获取最后一个元素的不同方法(有几个<hour>元素和另外两个,但只有最后一个<hour>元素是所需的目标),例如:

XDocument xDoc = XDocument.Load("Source.xml");          
XElement lastHour = doc.Root.Elements("hour").Last();

它对我不起作用。 当我在Elements("hour")之后放下 'dot' ,尝试调用Last()方法时,SharpDevelop 看不到它。 它出什么问题了?

整个代码块是:

if (hour == hisDoc.Root.Elements("hour").Last) {
     if ((hisDoc.Element("scanerHIS").Element("constants") != null) && (fcsDay.XPathSelectElement("constants") == null)) {
     fcsDay.Add(new XElement("constants",
          new XAttribute("P001", hisDoc.Root.XPathSelectElement("constants").Attribute("P001").Value),
          new XAttribute("Q001", hisDoc.Root.XPathSelectElement("constants").Attribute("Q001").Value),
          new XAttribute("N2", hisDoc.Root.XPathSelectElement("constants").Attribute("N2").Value),
          new XAttribute("CO2", hisDoc.Root.XPathSelectElement("constants").Attribute("CO2").Value)));
     }
}
fcsDoc.Save(FCSfileName); 

首先,感谢所有帮助过的人。

我需要使用System.Linq编写,因为 System.Xml.Linq 不包含Last()方法。

答案是:

if (hour == hisDoc.Root.Descendants("hour").Last())

暂无
暂无

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

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