Concatenate two node values

2019-08-11 09:53发布

问题:

I have the following XML structure, and I need to combine the values of handlingInstructionText:

<handlingInstruction>
    <handlingInstructionText>CTAC  |  MARTINE HOEYLAERTS</handlingInstructionText>
</handlingInstruction>
<handlingInstruction>
    <handlingInstructionText>PHON  |  02/7225235</handlingInstructionText>
</handlingInstruction>

My expected output is

CTAC  |  MARTINE HOEYLAERTS PHON  |  02/7225235

I'm currently using the string-join function but it seems not supported by the version of xsl that I'm currently using.

<xsl:value-of select="otxsl:var-put('Join2_handlingInstructionText',
string-join(handlingInstruction/concat(handlingInstructionText/text(),
' ', handlingInstructionText/text())))" />

I already tried using a for-each function to get each value but I want it to make it a 1 line code only.

回答1:

XSLT 1.0

<xsl:value-of select="concat(handlingInstruction[1]/handlingInstructionText,
                             ' ',
                             handlingInstruction[2]/handlingInstructionText)"/>

will return your expected output:

CTAC | MARTINE HOEYLAERTS PHON | 02/7225235

for your given input XML:

<r>
  <handlingInstruction>
      <handlingInstructionText>CTAC  |  MARTINE HOEYLAERTS</handlingInstructionText>
  </handlingInstruction>
  <handlingInstruction>
      <handlingInstructionText>PHON  |  02/7225235</handlingInstructionText>
  </handlingInstruction>
</r>

assuming r is the current node. Click to try


Update: So, in the context of your var-put extension, this would be:

<xsl:value-of select=
              "otxsl:var-put('Join2_handlingInstructionText',
                              concat(handlingInstruction[1]/handlingInstructionText,
                                     ' ',
                                     handlingInstruction[2]/handlingInstructionText))"/>


回答2:

I already tried using a for-each function to get each value but I want it to make it a 1 line code only.

You should make it as many lines as it takes. As it happens, you could use:

<xsl:apply-templates select="handlingInstruction/handlingInstructionText"/>

to produce the desired result, but:

<xsl:for-each select="handlingInstruction">
    <xsl:value-of select="handlingInstructionText"/>
</xsl:for-each>

is perfectly fine, too.


Note: Both of the above suggestions assume a well-formed input such as:

<root>
    <handlingInstruction>
        <handlingInstructionText>CTAC  |  MARTINE HOEYLAERTS</handlingInstructionText>
    </handlingInstruction>
    <handlingInstruction>
        <handlingInstructionText>PHON  |  02/7225235</handlingInstructionText>
    </handlingInstruction>
</root>

and a a template matching root.