Darius
Darius

Reputation: 5

XSLT_1 - get second element from few different sources

I have two different input files which will be handle by one xslt. How can I get the second child element 'node' segment from first input and second 'group' element segment from the second input.

sample of first input file:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <node>
    <count>1</count>
    <value>111</value>
  </node>
  <node>
    <count>2</count>
    <value>222</value>
  </node>
  <node>
    <count>3</count>
    <value>333</value>
  </node>
</root>

Sample of second input file:

<?xml version="1.0" encoding="utf-8"?>
    <root>
      <group>
        <count>1</count>
        <value>111</value>
      </group>
      <group>
        <count>2</count>
        <value>222</value>
      </group>
      <group>
        <count>3</count>
        <value>333</value>
      </group>
    </root>

Script below doesn't work. Could you please assist how to fix it.

<xsl:template match="*[local-name()= 'root']">

    <xsl:variable name="unknown">
      <xsl:if test="normalize-space(*[2]) = 'node'">
        <xsl:value-of select="*[local-name()= 'node'][2]"/>
      </xsl:if>
      <xsl:if test="normalize-space(*[2]) = 'group'">
        <xsl:value-of select="*[local-name()= 'group'][2]"/>
      </xsl:if>
    </xsl:variable>

    <xsl:copy-of select="$unknown"/>

  </xsl:template>

Expect outputs are:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <node>
    <count>2</count>
    <value>222</value>
  </node>
</root>

or

<?xml version="1.0" encoding="utf-8"?>
<root>
  <group>
    <count>2</count>
    <value>222</value>
  </group>
</root>

Thank you, Darius

Upvotes: 0

Views: 33

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117083

How about:

<xsl:template match="/root">
    <xsl:copy>
        <xsl:copy-of select="*[2]"/>
    </xsl:copy>
</xsl:template>

or:

<xsl:template match="/root">
    <xsl:copy>
        <xsl:copy-of select="(node|group)[2]"/>
    </xsl:copy>
</xsl:template>

Upvotes: 1

Related Questions