Omit unneeded namespaces from the output

2019-02-13 11:17发布

My XSLT is outputiung some tags with xmlns:x="http://something" attribute... How to avoid this redundant attribute? The output XML never use, neither in a the x:tag, nor in an x:attribute.


EXAMPLE OF XML:

<root><p>Hello</p><p>world</p></root>

EXAMPLE OF XSL:

<xsl:transform version="1.0" 
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
   xmlns:xlink="http://www.w3.org/1999/xlink">
<xsl:output encoding="UTF-8" method="xml" version="1.0" indent="no"/>

<xsl:template match="root"><foo>
   <xsl:for-each select="p">
    <p><xsl:value-of select="." /></p>
   </xsl:for-each></foo>
   <xsl:for-each select="x">
    <link xlink:href="{x}" />
   </xsl:for-each></foo>
</xsl:template>

EXAMPLE OF XML OUTPUT:

<foo>
   <p xmlns:xlink="http://www.w3.org/1999/xlink">Hello</p>
   <p xmlns:xlink="http://www.w3.org/1999/xlink">world</p>
</foo>

The xmlns:xlink is a overhead, it is not used!


A typical case where XSLT must use namespace but the output not:

 <xsl:value-of select="php:function('regFunction', . )" />

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-13 11:45

As Dimitre has already said, if you are not using the xlink namespace anywhere in your XSLT, you should just remove its namespace declaration. If, however, your XSLT is actually using it somewhere that you haven't shown us, you can prevent it from being output by using the exclude-result-prefixes attribute:

<xsl:transform version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   exclude-result-prefixes="xlink">
查看更多
该账号已被封号
3楼-- · 2019-02-13 11:49

Just remove this namespace declaration from the xsl:stylesheet instruction -- it isn't used (and thus necessary) at all:

xmlns:xlink="http://www.w3.org/1999/xlink"

The whole transformation now becomes:

<xsl:transform version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output encoding="UTF-8" method="xml" version="1.0" indent="no"/>

 <xsl:template match="root"><foo>
   <xsl:for-each select="p">
   <p class="a"><xsl:value-of select="." /></p>
   </xsl:for-each></foo>
 </xsl:template>
</xsl:transform>

and when applied on the provided XML document:

<root><p>Hello</p><p>world</p></root>

produces result that is free of namespaces:

<foo>
    <p class="a">Hello</p>
    <p class="a">world</p>
</foo>
查看更多
登录 后发表回答