简体   繁体   English

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

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

I've come across different ways of getting the last element (there are several <hour> elements and two other but only the last <hour> element is the target needed) on the following link , eg:我遇到了以下链接上获取最后一个元素的不同方法(有几个<hour>元素和另外两个,但只有最后一个<hour>元素是所需的目标),例如:

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

It doesn't work for me.它对我不起作用。 When I put down 'dot' after Elements("hour") , trying to call Last() method, SharpDevelop doesn't see it.当我在Elements("hour")之后放下 'dot' ,尝试调用Last()方法时,SharpDevelop 看不到它。 What's wrong with it?它出什么问题了?

The whole block of code is:整个代码块是:

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); 

Firstly, thanks to everyone who helped.首先,感谢所有帮助过的人。

I need to write using System.Linq , because System.Xml.Linq doesn't contain Last() method.我需要使用System.Linq编写,因为 System.Xml.Linq 不包含Last()方法。

The answer is:答案是:

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

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

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