【问题标题】:c# How to fetch targetNamespace from XML documentc# 如何从 XML 文档中获取 targetNamespace
【发布时间】:2020-03-18 14:38:35
【问题描述】:

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

    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 属性来访问值

    【讨论】:

      猜你喜欢
      • 2019-12-28
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多