Yogesh Jadhav
Yogesh Jadhav

Reputation: 137

Xslt to transform element to array element

My business requirement is to transform below input XML into transformed XML.

Input XML is as below

<root>   
    <name>football</name>  
    <pageTitle>League</pageTitle>  
    <pageMetaDescription>Inter City League</pageMetaDescription>     
</root>

Output Xml that is expected after the XSLT based transformation is

<root>  
  <Array>
    <name>name</name>
    <text>football</text>      
    <format>plainText</format>
  </Array>
  <Array>
    <name>pageTitle</name>
    <text>League</text>      
    <format>plainText</format>
  </Array>
  <Array>
    <name>pageMetaDescription</name>
    <text>Inter City League</text>      
    <format>plainText</format>
  </Array>   
</root>  

In-order to Perform such tranformation I am not able to write XSLT.
Can anyone let me know how to write such XSLT for such requirement.

Upvotes: 0

Views: 880

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 31011

You wrote I am not able to write XSLT, but I read it as my knowledge of XSLT is too limited and need help how to do it. Anyway, you marked this question a.o. with just XSLT!

The template matching root is quite similar to the identity teplate.

But the template matching its child elements is more complicated:

  • Start with Array opening tag.
  • Then write its content including:
    • name tag with value equal to the name of the tag (name()).
    • text tag with value equal to the content of the tag (.).
    • format tag with content of plainText.
  • End with Array closing tag.

So the whole script can look like below:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes" />

  <xsl:template match="root">
    <root>
      <xsl:apply-templates/>
    </root>
  </xsl:template>

  <xsl:template match="root/*">
    <Array>
      <name><xsl:value-of select="name()"/></name>
      <text><xsl:value-of select="."/></text>
      <format>plainText</format>
    </Array>
  </xsl:template>
</xsl:transform>

You didn't write it, but if you have other cases of source tags with format other than plainText (e.g. date), you have to write other templates (matching these tag names), with respective details written another way.

Upvotes: 1

Related Questions