c# 如何从 XML 文档中获取 targetNamespace

c# How to fetch targetNamespace from XML document

我有以下 XML 个文件:

<ABC: EXAMPLE xmlns: ABC = "www.xyz.com" targetNamespace = "www.pqr.com">
//BODY
</ABC:EXAMPLE>

<ORDER targetNamespace = "www.pqr.com">
BODY
</ORDER>

我试过了-

 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.LoadXml(xmlstring);
 xmlNamespace = xmlDoc.DocumentElement.NamespaceURI;

但这只会return我www.xyz.comnull分别来自上面两个文件

如何获取 targetNamespace

targetNamespace 是 XML 元素 ABC:EXAMPLE 上的一个属性,而不是标准的 XML,所以没有直接在 属性 XmlDocument 供您获取。您需要使用 Attributes 属性 访问它。像这样:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlstring);

// This is the namespace of the element 'ABC:EXAMPLE', so "www.xyz.com"
xmlNamespace = xmlDoc.DocumentElement.NamespaceURI;

// This is the value of the attribute 'targetNamespace', so "www.pqr.com"
xmlTargetNamespace = xmlDoc.DocumentElement.Attributes["targetNamespace"].Value;

您可以在任何 XmlElement 上使用属性 属性 来访问它的属性,您可以在 XmlNode 上使用命名索引和值 属性 来访问值