[英]How to get node attributes of specific type in xml?
I am using the following code: 我正在使用以下代码:
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]");
}
The problem is that document.DocumentElement.SelectNodes("//char[@confidence]") returns null. 问题是document.DocumentElement.SelectNodes(“ // char [@confidence]”)返回null。
When I write the following code the result is shown. 当我编写以下代码时,将显示结果。
int nodesCount = Document.DocumentElement.ChildNodes[0].ChildNodes.Count;
How do I count all nodes with attributes confidence? 如何计算所有具有属性置信度的节点?
You could use XDocument and some effective LINQ: 您可以使用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();
Output: 4 输出4
And my file.xml contains the following: 我的file.xml包含以下内容:
<something>
<char confidence="1">
</char>
<char confidence="2">
</char>
<char confidence="3">
</char>
<notchar confidence="1">
</notchar>
</something>
The above code checks all descendants for the attribute "confidence". 上面的代码检查所有后代的属性“ confidence”。 If you want only elements that have the name "char", you can use the following:
如果只需要名称为“ char”的元素,则可以使用以下内容:
int count = doc.Root.Descendants().Count(e => e.Name == "char" && e.Attribute("confidence") != null);
Output: 3 输出3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.