Ajeet Singh
Ajeet Singh

Reputation: 1086

how to parent tag with nested tag

I have an XML File that looks like this:

<SNS>
<SN>aaaa</SN>
<SN>bbbb</SN>
<LN>cccc</LN>
<SN>dddd</SN>
<SN>eeee</SN>
<LN>ffff</LN>
</SNS>

Required Output:

<SN>aaaa</SN>
<LN>cccc</LN>
<SN>bbbb</SN>
<LN>cccc</LN>
<SN>dddd</SN>
<LN>ffff</LN>
<SN>eeee</SN>
<LN>ffff</LN>

How to add every <SN> tag with <LN>?

Upvotes: 1

Views: 35

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167781

Just process all SN elements and in their template copy the following sibling LN:

  <xsl:template match="SNS">
      <xsl:apply-templates select="SN"/>
  </xsl:template>  

  <xsl:template match="SN">
      <xsl:copy-of select="., following-sibling::LN[1]"/>
  </xsl:template>

https://xsltfiddle.liberty-development.net/pPzifq2

In XSLT 3 you could also simply process each SN and its sibling LN and push them through the identity transformation:

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="SNS">
      <xsl:apply-templates select="SN!(., following-sibling::LN[1])"/>
  </xsl:template>

https://xsltfiddle.liberty-development.net/pPzifq2/1

Upvotes: 2

Related Questions