Rose
Rose

Reputation: 1498

Convert XML file into another XML file using XSL template

I want to convert an XML into another XML using an XSLT stylesheet.

This is the part of my input XML where I have to use XSL template(input.xml):

 ...
    <extension>
        <og:image>http://www.example.com/images/logos/logo-example-PNG.png</og:image>
        <og:type>article</og:type>
        <resourceName>http://www.example.com/big-data-search-managed-services-questions</resourceName>
    </extension>
   .......

I want my XML(output.xml) to look like this:

....
<MT N="og:image" V="http://www.example.com/images/logos/logo-example-PNG.png"/>
<MT N="og:type" V="article"/>
<MT N="resourceName" V="http://www.example.com/big-data-search-managed-services-questions"/>
...

I am trying to use an XSLT for this. But I am stuck at the XSL template part. I want my XSLT to go in the XPATH of extension and specify a template for every element inside of the extension to convert into this form:

<MT N="" V=""/>

"N" with the name of the tag name and "V" with the value of the tag

What should I specify in my XSLT?

 <xsl:template match="/extension">
    ....
    </xsl:template>

Upvotes: 1

Views: 604

Answers (1)

Rudramuni TP
Rudramuni TP

Reputation: 1276

Try this:

XML:

<extension xmlns:og="http://og.com">
 <og:image>http://www.example.com/images/logos/logo-example-PNG.png</og:image>
 <og:type>article</og:type>
 <resourceName>http://www.example.com/big-data-search-managed-services-questions</resourceName>
</extension>

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:og="http://og.com">

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="extension">
    <xsl:for-each select="*">
        <xsl:element name="MT">
            <xsl:attribute name="N" select="name()"/>
            <xsl:attribute name="V" select="."/>
        </xsl:element>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

OutPut:

<MT N="og:image" V="http://www.example.com/images/logos/logo-example-PNG.png"/>
<MT N="og:type" V="article"/>
<MT N="resourceName" V="http://www.example.com/big-data-search-managed-services-questions"/>

Edited input XML:

<root  xmlns:og="http://og.com">
 <extension>
  <og:image>http://www.example.com/images/logos/logo-example-PNG.png</og:image>
  <og:type>article</og:type>
  <resourceName>http://www.example.com/big-data-search-managed-services-questions</resourceName>
 </extension>
</root>

Here 'root' is the root element, namespace can be declared there.

Upvotes: 1

Related Questions