【发布时间】: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