如何在特定标记 XMLDocument C# 中的标记上使用 GetElementsByTagName

How to use GetElementsByTagName on a Tag That Is Insıde a Spesific Tag XMLDocument C#

我需要读取一个 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");

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

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

//cac:InvoiceLine/cac:AllowanceCharge

还有一个办法

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

通过XPath对select节点调用SelectNodes方法:

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

或重载方法

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