我有以下 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.com
和 null
分别来自上述两个文件。我如何获取
targetNamespace
?
最佳答案
targetNamespace
是 XML 元素的一个属性 ABC:EXAMPLE
,而不是标准的 XML,所以没有直接在 XmlDocument 上的属性供您获取。您需要使用 Attributes
访问它属性(property)。像这样:
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 属性来访问该值
关于c# 如何从 XML 文档中获取 targetNamespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58995668/