在XSL Translation中更改XML文件的名称空间 [英] Changing namespace for XML file in XSL Translation

查看:122
本文介绍了在XSL Translation中更改XML文件的名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个输入文件,该文件在默认名称空间(xmlns="companyURL")中使用公司的名称空间,但我希望输出文件使用默认名称空间(xmlns:cmp="companyURL")以外的其他名称.因此,我使用cmp命名空间构造了文件,​​但随后我想复制一些内部元素:

So I have an input file that uses my company's namespace in the default namespace (xmlns="companyURL") but I want my output file to use something other than the default namespace (xmlns:cmp="companyURL"). So I construct my file using the cmp namespace, but then I want to copy some of the inner elements:

<xsl:element name="cmp:container">
  <xsl:for-each select="foo">
    <xsl:copy-of select="." />
  </xsl:for-each>
</xsl:element>

不幸的是,这样做是为每个内部元素定义了默认的命名空间,从而使文件变得非常冗长和丑陋.简化示例:

Unfortunately, what this does is define the default namespace for each of those inner elements, making the file incredibly verbose and ugly. Simplified example:

来源:

<foo xmlns="companyURL">
  <num1>asdf</num1>
  <num2>ghjkl</num2>
</foo>

变成:

<cmp:container xmlns:cmp="companyURL">
  <num1 xmlns="companyURL">asdf</num1>
  <num2 xmlns="companyURL">ghjkl</num2>
</cmp:container>

当然,companyURL又大又长又丑陋,而且在两个地方都一样,所以我希望上面的结果如下:

Of course, companyURL is big and long and ugly, and it's the same in both places, so I would prefer the above result to just be the following:

<cmp:container xmlns:cmp="companyURL">
  <cmp:num1>asdf</cmp:num1>
  <cmp:num2>ghjkl</cmp:num2>
</cmp:container>

是否有一种简单的方法来执行此操作,还是应该将cmp名称空间下的所有内容都转换为默认名称空间?如果可能的话,我宁愿使用显式命名空间命名,这有助于我体会XSLT的理解.

Is there an easy way to do this, or should I convert everything under the cmp namespace to the default namespace? I would prefer to use the explicit namespace naming if possible, it aids in understanding the XSLT in my experience.

推荐答案

此转换:

 <xsl:template match="*">
     <xsl:element name="cmp:{name()}" namespace="CompanyURL">
       <xsl:copy-of select="@*"/>
       <xsl:apply-templates/>
     </xsl:element>
 </xsl:template>
 <xsl:template match="/*">
     <cmp:container xmlns:cmp="CompanyURL">
       <xsl:copy-of select="@*"/>
       <xsl:apply-templates/>
     </cmp:container>
 </xsl:template>
</xsl:stylesheet>

在提供的XML文档上执行时:

<foo xmlns="companyURL">
  <num1>asdf</num1>
  <num2>ghjkl</num2>
</foo>

产生想要的正确结果:

<cmp:container xmlns:cmp="CompanyURL">
   <cmp:num1>asdf</cmp:num1>
   <cmp:num2>ghjkl</cmp:num2>
</cmp:container>

这篇关于在XSL Translation中更改XML文件的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆