Bhuvanesh Kumar
Bhuvanesh Kumar

Reputation: 1

How to bring the value of a multi valued Sub tags with different parent tags under a common header tag in XSLT

I am trying to print the values in a loop for multiple occurences where one of the value's header tag is different from the other. The count of the child3 tag may be more than the child1 tag but the third occurence of child3 tag will be ignored as only two occurence of child1 tag is available.

<?xml version="1.0" encoding="UTF-8"?>
<Parent1>
  <Parent2>
    <child1>JOHN ONE</child1>
    <child1>JOHN TWO</child1>
    <child2>JACK ONE</child2>
    <child2>JACK TWO</child2>
  </Parent2>
  <child3>JAMES ONE</child3>
  <child3>JAMES TWO</child3>
  <child3>JAMES THREE</child3>
</Parent1>

The code i tried:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
      <xsl:for-each select="Parent1">
<Children >
<child1>
        <xsl:value-of select="Parent2/child1" />
</child1>
<child2>
        <xsl:value-of select="Parent2/child2" />
</child2>
<child3>
        <xsl:value-of select="child3" />
</child3>
</Children>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Actual output I got:

<Children>
  <child1>JOHN ONE</child1>
  <child2>JACK ONE</child2>
  <child3>JAMES ONE</child3>
</Children>

The expected output is:

<Children>
  <child1>JOHN ONE</child1>
  <child2>JACK ONE</child2>
  <child3>JAMES ONE</child3>
</Children>
<Children>
  <child1>JOHN TWO</child1>
  <child2>JACK TWO</child2>
  <child3>JAMES TWO</child3>
</Children>

Upvotes: 0

Views: 20

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117175

With the given input, the expected output could be produced using:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/Parent1">
    <xsl:for-each select="Parent2/child1">
        <xsl:variable name="i" select="position()" />
        <Children>
            <xsl:copy-of select="."/>
            <xsl:copy-of select="../child2[$i]"/>
            <xsl:copy-of select="/Parent1/child3[$i]"/>
        </Children>
    </xsl:for-each> 
</xsl:template>

</xsl:stylesheet>

Do note that the output is an XML fragment, not a well-formed XML document.

Upvotes: 0

Related Questions