Home > front end >  XSLT picking element in specific order and create element
XSLT picking element in specific order and create element

Time:06-13

We have one XML which is required to be in specific format as output using xslt. I am new to this xslt and have tried multiple approaches like:

Making template of every tag, and tried to call template like one element from each template, however this is not happening.

Sample payload
<inputs>
  <field>0</field>
  <type1>1</type1>
  <type2>2</type2>
  <type3>3</type3>
  <category1>4</category1>
  <category2>5</category2>
  <category3>6</category3>
</inputs>

Below is the desired output
output xml
<tag>
  <type1>1</type1>
  <category1>4</category1>
</tag>
<tag>
  <type2>2</type2>
  <category2>5</category2>
</tag>
<tag>
  <type3>3</type3>
  <category3>6</category3>
</tag>

CodePudding user response:

In the given example, you could do:

<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:template match="/inputs">
    <xsl:for-each select="*[starts-with(name(), 'type')]">
        <xsl:variable name="i" select="position()" />
        <tag>
            <xsl:copy-of select="."/>
            <xsl:copy-of select="../*[starts-with(name(), 'category')][$i]"/>
        </tag>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

to get the output you show.

However, it's not clear if the example represents the actual rules than need to be applied here.

Note also that the result is an XML fragment, missing a single root element.

  • Related