C# 在 xml 中合并命名空间引用

标签 c# xml xslt namespaces prefix

我有由原子格式化程序格式化的 xml。
原子格式化程序似乎多次内联指定命名空间。

有什么方法可以轻松地整合这些。
下面的示例显示了为每个属性指定了 3 次的命名空间。
这太可怕了。

我想要文档顶部的前缀,并且文档中没有命名空间(只是前缀)。是否有编写器或格式化程序选项来实现这一目标?

<property p3:name="firstname" xmlns:p3="http://a9.com/-/opensearch/extensions/property/1.0/" xmlns="http://a9.com/-/opensearch/extensions/property/1.0/">Drikie</property>

谢谢

克雷格。

最佳答案

The atom formatter seems to specify namespaces inline multiple times.

Is there any way to easily consolidate these. The example below shows namespaces specified three times for each property. This is horrible.



生成这种更紧凑格式的最简单方法是对 XML 文档应用以下 XSLT 转换 :
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="node()[not(self::*)]|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="*">
  <xsl:element name="{name()}" namespace="{namespace-uri()}">
   <xsl:copy-of select="descendant::*/namespace::*"/>
   <xsl:copy-of select="namespace::*"/>

   <xsl:apply-templates select="node()|@*"/>
  </xsl:element>
 </xsl:template>
</xsl:stylesheet>

例如,当应用于以下 XML 文档 时(基于你的问题):
<t xmlns="http://a9.com/-/opensearch/extensions/property/1.0/">
<property p3:name="firstname"
  xmlns:p3="http://a9.com/-/opensearch/extensions/property/1.0/"
  xmlns="http://a9.com/-/opensearch/extensions/property/1.0/"
  >Drikie</property>
</t>

产生了想要的结果 :
<t
 xmlns="http://a9.com/-/opensearch/extensions/property/1.0/"
 xmlns:p3="http://a9.com/-/opensearch/extensions/property/1.0/">
    <property p3:name="firstname">Drikie</property>
</t>

请注意 :
  • 命名空间声明不能在具有将相同前缀绑定(bind)到另一个命名空间的声明的元素之上进一步提升 .
  • 将命名空间声明提升为祖先元素可能会增加解析的 XML 文档的大小 ,因为所有命名空间节点都会向下传播到所有后代节点,其中一些可能根本不需要该命名空间。
  • 关于C# 在 xml 中合并命名空间引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3385069/

    相关文章:

    c# - 改善互联网速度较低且使用远距离托管的 WCF Web 服务的 Windows 窗体客户端的用户体验

    c# - 使用前检查通用列表中的项目

    php - Xpath访问XML标记内的属性值

    xml - 使用 Xpath 进行 XSLT 处理的说明

    xml - XSLT 将 XML 同级移至子级

    c# - 使用 C# 的 VMware vCenter API - InitiateFileTransferToGuest 失败

    java - 只读取 XML 中的根元素

    xml - Oracle中使用变量定义XMLTable中的路径

    xml - 如何使用 XSLT 递归删除一些 xml 元素

    javascript - 在我的服务器上配置 JavaScript Google Maps API 时出现问题