[英]How do I find the maximum value of an attribute value in an XML file?
I have an XML file with the following structure: 我有一个XML文件,具有以下结构:
<doc>
<rootelement>
<childelement id="0" />
<childelement id="1" />
.
.
</rootelement>
</doc>
I want to find the highest numeric value of the id
attribute 我想找到
id
属性的最高数值
The idea I have in mind is something like: 我想到的想法是这样的:
int highest = -1;
foreach(var node in xmldoc.SelectNodes("//doc/rootelement/childelement"))
{
highest = Math.Max(GetID(node), highest);
}
where GetID(XMLNode)
would retrieve the value of the attribute of the current node. 其中
GetID(XMLNode)
将检索当前节点的属性值。
Is there a more compact (or more efficient) XPath expression to do that? 是否有更紧凑(或更有效)的XPath表达式来做到这一点?
You can use Linq to Xml: 你可以使用Linq到Xml:
var xdoc = XDocument.Load(path_to_xml);
var maxId = xdoc.XPathSelectElements("//doc/rootelement/childelement")
.Max(c => (int)c.Attribute("id"));
Or without XPath: 或者没有XPath:
var maxId = xdoc.Root.Elements("rootelement")
.Elements("childelement")
.Max(c => (int)c.Attribute("id"));
With XmlDocument: 使用XmlDocument:
var maxId = doc.SelectNodes("//doc/rootelement/childelement")
.Cast<XmlElement>()
.Max(c => Int32.Parse(c.Attributes["id"].Value));
Use Linq to XML. 使用Linq to XML。
string xml =
@"<doc>
<rootelement>
<childelement id='0' />
<childelement id='1' />
</rootelement>
</doc>";
var doc = XDocument.Parse(xml);
int max = doc.Descendants("childelement").Max(e => (int)e.Attribute("id"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.