concatenation two fields in xsl

后端 未结 2 659
后悔当初
后悔当初 2021-01-27 04:31

I have a some xml fields i need to concatenate all the fields in one field


example

        
相关标签:
2条回答
  • 2021-01-27 04:59

    This short and simple (no explicit conditional instructions) XSLT 1.0 transformation:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
     <xsl:template match="/*">
      <fields>
        <field name="all">
          <xsl:variable name="vfieldConcat">
            <xsl:for-each select="field/value">
              <xsl:value-of select="concat(., ' ')"/>
            </xsl:for-each>
          </xsl:variable>
          <value><xsl:value-of select=
             "normalize-space($vfieldConcat)"/></value>
        </field>
      </fields>
     </xsl:template>
    </xsl:stylesheet>
    

    when applied on the provided XML document (corrected for well-formedness):

    <fields>
        <field name="first">
            <value>example</value>
        </field>
        <field name="last">
            <value>hello</value>
        </field>
        <field name="age">
            <value>25</value>
        </field>
        <field name="enable">
            <value>1</value>
        </field>
    </fields>
    

    produces the wanted, correct result:

    <fields>
       <field name="all">
          <value>example hello 25 1</value>
       </field>
    </fields>
    

    II. XSLT 2.0 solution

    <xsl:stylesheet version="2.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
     <xsl:template match="/*">
      <fields>
        <field name="all">
          <value><xsl:value-of select="field/value"/></value>
        </field>
      </fields>
     </xsl:template>
    </xsl:stylesheet>
    

    When this transformation is applied on the same XML document (above), the same correct result is produced:

    <fields>
       <field name="all">
          <value>example hello 25 1</value>
       </field>
    </fields>
    

    Explanation: Using the fact that the default value for the separator attribute of xsl:value-of is a single space.

    0 讨论(0)
  • 2021-01-27 05:09

    something like:

    ...
    <fields>
    <field name="all">
        <value><xsl:apply-templates select="fields/field"/></value>
    </field>
    </fields>
    ...
    <xsl:template match="field[value/text()]">
      <xsl:value-of select="value"/>
      <xsl:if test="position() != last()"><xsl:text> </xsl:text></xsl:if>
    </xsl:template>
    ...
    
    0 讨论(0)
提交回复
热议问题