开发者

Changing namespace for XML file in XSL Translation

开发者 https://www.devze.com 2023-01-11 09:30 出处:网络
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=\"compa

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:

Source:

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

Turns into:

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

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>

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.


This transformation:

 <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>

when performed on the provided XML document:

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

produces the wanted, correct result:

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

精彩评论

暂无评论...
验证码 换一张
取 消