Concatenate data into one variable

2019-09-11 08:46发布

问题:

An XML file has data like:

<AddtlStsRsnInf>/00000002/Level 2 Reject</AddtlStsRsnInf> 
<AddtlStsRsnInf>The Transaction Reference Number is</AddtlStsRsnInf> 
<AddtlStsRsnInf>not unique.</AddtlStsRsnInf>  

How do you concatenate the data from all the three tags into a variable?

Thanks and regards,

Kiran

回答1:

This may help:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template name="concat" match="/data">
  <xsl:for-each select="AddtlStsRsnInf">
    <xsl:value-of select="." />
    <xsl:if test="position() != last()">
      <xsl:text> </xsl:text>
    </xsl:if>
  </xsl:for-each>
</xsl:template> 

</xsl:stylesheet>

Given:

<?xml version="1.0"?>
<data>
<AddtlStsRsnInf>/00000002/Level 2 Reject</AddtlStsRsnInf> 
<AddtlStsRsnInf>The Transaction Reference Number is</AddtlStsRsnInf> 
<AddtlStsRsnInf>not unique.</AddtlStsRsnInf>  
</data>

You can wrap it in a variable (v) using:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template name="concat" match="/data">
  <xsl:variable name="v">
    <xsl:for-each select="AddtlStsRsnInf">
      <xsl:value-of select="." />
      <xsl:if test="position() != last()">
        <xsl:text> </xsl:text>
      </xsl:if>
    </xsl:for-each>
  </xsl:variable>

  <xsl:value-of select="$v" />
</xsl:template> 

</xsl:stylesheet>


回答2:

I think you would use something like:

<xsl:variable name="myVar" select="fn:string-join(//AddtlStsRsnInf/text(), ' ')" />

You'll need to adjust the XPath query if you're only supposed to select some AddtlStsRsnInf nodes.