【问题标题】:How to get node attributes of specific type in xml?如何在xml中获取特定类型的节点属性?
【发布时间】:2014-06-25 12:28:31
【问题描述】:

我正在使用以下代码:

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;

如何计算所有具有属性置信度的节点?

【问题讨论】:

  • SelectNodes 总是返回一个 XmlNodeList 并且永远不会为空。
  • 但在我的代码中它返回 null.count =0
  • 如果 XmlNodeList 为空但结果是 XmlNodeList 而不是 null,则 Count 当然可以为零。向我们展示您的 XML 文档,我们可以帮助您处理 XPath 表达式。或者尝试//*[@confidence],这样生成的XmlNodeList 应该包含所有具有confidence 属性的元素。
  • 感谢 Martin Honnen,我得到了 //*[@confidence] 的结果。

标签: c# asp.net xml xslt


【解决方案1】:

您可以使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多