xslt concatenate text from nodes

二次信任 提交于 2019-12-06 04:55:25

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*/*">
  <xsl:value-of select="concat(name(),'=',@value)"/>

  <xsl:if test="not(position()=last())">
    <xsl:text>&amp;</xsl:text>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<args>
  <sometag value="abc"/>
  <anothertag value="def"/>
  <atag value="blah"/>
</args>

produces the wanted, correct result:

sometag=abc&anothertag=def&atag=blah

I ended up realizing I could just use a for-each loop.. I'm not sure why I didnt use that to begin with. I'm still wondering how I could recursively iterate a list of adjacent nodes the way I was doing before (which wasn't working correctly because it was also catching text nodes and doing other weird things I couldn't understand). Here is my solution (I also added a separator variable)

<xsl:template name='string_builder'>
    <xsl:param name='data' />
    <xsl:param name='separator' />        
    <xsl:for-each select='$data/*'>
        <xsl:value-of select='name()'/>=<xsl:value-of select='@value'/>
        <xsl:if test='position() != last()'>
           <xsl:value-of select='$separator'/>
        </xsl:if>
    </xsl:for-each>
</xsl:template>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!