Omit unneeded namespaces from the output

大憨熊 提交于 2019-11-30 04:50:55

问题


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', . )" />

回答1:


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



回答2:


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>


来源:https://stackoverflow.com/questions/15582825/omit-unneeded-namespaces-from-the-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!