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

问题描述 投票:1回答:1

我有以下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;

但是这只会分别从上述两个文档中返回www.xyz.comnull

我如何获取targetNamespace

c# xml xsd namespaces xml-namespaces
1个回答
0
投票

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上使用Attributes属性来访问其属性,可以在XmlNode上使用命名索引和Value属性来访问值

© www.soinside.com 2019 - 2024. All rights reserved.