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.
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 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
And my file.xml contains the following:
<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". If you want only elements that have the name "char", you can use the following:
int count = doc.Root.Descendants().Count(e => e.Name == "char" && e.Attribute("confidence") != null);
Output: 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.