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

问题描述 投票:0回答:1

我遇到了在<hour>上获取最后一个元素(有几个<hour>元素和另外两个,但只有最后一个following link元素是需要的目标)的不同方式,例如:

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

对我不起作用。当我在Elements("hour")之后放下“点”时,尝试调用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); 
c# xml linq-to-xml xelement
1个回答
0
投票

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

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

答案是:

if (hour == hisDoc.Root.Descendants("hour").Last())
© www.soinside.com 2019 - 2024. All rights reserved.