【问题标题】:How to use GetElementsByTagName on a Tag That Is Insıde a Spesific Tag XMLDocument C#如何在特定标记 XMLDocument C# 中的标记上使用 GetElementsByTagName
【发布时间】:2020-07-12 23:40:25
【问题描述】:

我需要读取一个 Xml 文件,并且我正在尝试计算文件中特定标签的数量。我的问题是同一个标签在其他标签外面和里面时代表不同的东西。我能够获得标签的总数,但我需要找到指定标签内的标签计数。

(我通过使用 XmlNodeList nodeList = xmlDoc.DocumentElement.GetElementsByTagName("cac:AllowanceCharge"); 找到总 cac:AllowanceCharge 标签)

要查找我尝试使用的“cac:InvoiceLine”标签内的“cac:AllowanceCharge”标签:

XmlNodeList elemList = root.GetElementsByTagName(@"//cac:InvoiceLine/cac:AllowanceCharge");

XmlNodeList elemList = root.GetElementsByTagName(@"//InvoiceLine/AllowanceCharge");

XmlNodeList elemList = root.GetElementsByTagName(@"cac:InvoiceLine/cac:AllowanceCharge");

如果有人能告诉我正确的语法,我将不胜感激。谢谢。

【问题讨论】:

    标签: c# xml xmldocument


    【解决方案1】:

    第一个看起来是正确的,如果你注册了命名空间绑定cac

    //cac:InvoiceLine/cac:AllowanceCharge
    

    还有一种方法

    //*[name()='InvoiceLine']/*[name()='AllowanceCharge']
    

    要通过 XPath 选择节点,请调用 SelectNodes 方法:

    var root = xmlDoc.DocumentElement;
    var nodeList = root.SelectNodes(xpath);
    

    或者重载的方法

    var nodeList2 = root.SelectNodes(xpath, namespaceManager);
    

    【讨论】:

    • 另一个问题,如何查找特定属性?我正在使用“//*[name()='InvoiceLine']/*[name()='AllowanceCharge']”
    • 这里有一些例子:w3schools.com/xml/xpath_syntax.asp
    • 很抱歉再次打扰,但我已经尝试过,但无法正确处理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    相关资源
    最近更新 更多