[英]How to get node attributes of specific type in xml?
我正在使用以下代码:
System.Xml.XmlDocument document = new System.Xml.XmlDocument();
document.Load(@"D:\Files\OCR\" + FileUpload1.FileName + ".xml");
if (document.HasChildNodes)
{
StringBuilder sb = new StringBuilder();
StringBuilder positions = new StringBuilder();
XmlElement root = document.DocumentElement;
XmlNodeList nodes = document.DocumentElement.SelectNodes("//char[@confidence]");
}
问题是document.DocumentElement.SelectNodes(“ // char [@confidence]”)返回null。
当我编写以下代码时,将显示结果。
int nodesCount = Document.DocumentElement.ChildNodes[0].ChildNodes.Count;
如何计算所有具有属性置信度的节点?
您可以使用XDocument和一些有效的LINQ:
XDocument doc = XDocument.Load(@"D:\Temp\file.xml");
int count = doc.Root.Descendants().Count(e => e.Attribute("confidence") != null);
Console.Write("Count:" + count);
Console.Read();
输出4
我的file.xml包含以下内容:
<something>
<char confidence="1">
</char>
<char confidence="2">
</char>
<char confidence="3">
</char>
<notchar confidence="1">
</notchar>
</something>
上面的代码检查所有后代的属性“ confidence”。 如果只需要名称为“ char”的元素,则可以使用以下内容:
int count = doc.Root.Descendants().Count(e => e.Name == "char" && e.Attribute("confidence") != null);
输出3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.