【问题标题】:How to get the last XElement of particular type C#, XML, LINQtoXML如何获取特定类型 C#、XML、LINQtoXML 的最后一个 XElement
【发布时间】:2020-03-16 13:42:25
【问题描述】:

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

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

【问题讨论】:

  • 你的使用中有 linq 对吗?
  • @Isparia,System.Xml.Linq,你是对的。
  • 另外尝试使用using System.Linq;,我不确定它是否会有所帮助。但它可能。
  • @Isparia,我刚刚尝试过:运算符“==”不能应用于“System.Xml.Linq.XElement”和“方法组”类型的操作数。我将编辑问题。
  • 使用后代而不是元素。

标签: c# xml linq-to-xml xelement


【解决方案1】:

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

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

答案是:

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

【讨论】:

  • 使用 Descendants 时不需要 Root。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 2013-10-24
  • 2012-02-24
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多