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

标签 c# xml xsd namespaces xml-namespaces

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

最佳答案

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/

相关文章:

xml - 是否可以将根元素限制为从指定父类型派生的类型?

c# - 元组无法序列化,因为它没有无参数构造函数

c# - LINQ 包含使用投影

java - Android TextView 和 ImageView 的布局问题

xml - 捕获 xml 标签和以下相关标签(如果存在)

xml - BizTalk::名称为 "X"且命名空间为 "Y"的开始元素是意外的

XML-XSD : How to define namespaces correctly?

c# - 如何对多个不同大小的矩形进行分类

c# - 是否可以从 C# 创建 SQL Server native 文件(如 BCP native 格式)

android - Android 中通过 xml 进行字符串格式化