[英]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.