Help me to trasform xml in another xml

Oxygen general issues.
liasti
Posts: 1
Joined: Tue Dec 22, 2015 5:38 pm

Help me to trasform xml in another xml

Post by liasti »

How can I transfom this xml:

Code: Select all

<Objects>
<object>
<Property Name="bname">Peter</Property>
<Property Name="age">12</Property>
<Property Name="color">
<Property>Blu</Property>
<Property>Red</Property>
<Property>Green</Property>
</Property>
</Object>
<object>
<Property Name="bname">Samuel</Property>
<Property Name="age">20</Property>
<Property Name="color">
<Property>Yellow</Property>
<Property>Red</Property>
</Property>
</Object>
</Objects>
in this xml:

Code: Select all

<Objects>
<object>
<bname>Peter</bname>
<age>12</age>
<colorAttr>
<attrColor colName="color">Blu</attrColor>
<attrColor colName="color">Red</attrColor>
<attrColor colName="color">Green</attrColor>
</colorAttr>
</Object>
<object>
<bname>Samuel</bname>
<age>20</age>
<colorAttr>
<attrColor colName="color">Yellow</attrColor>
<attrColor colName="color">Red</attrColor>
</colorAttr>
</Object>
</Objects>

Help me. Please.
tavy
Posts: 388
Joined: Thu Jul 01, 2004 12:29 pm

Re: Help me to trasform xml in another xml

Post by tavy »

Hello,

Below you can find a stylesheet to transform your source XML. You just need to create a transformation scenario and apply it over the source file.
Please note that tour source an destination files that you posted are not well formed. The end tag of the object element is written with uppercase, it is "</Object>" instead of "</object>".

Code: Select all


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<!-- Match document -->
<xsl:template match="/">
<xsl:apply-templates mode="copy" select="."/>
</xsl:template>

<xsl:template match="Property[@Name='bname']" mode="copy">
<bname><xsl:apply-templates mode="copy"/></bname>
</xsl:template>

<xsl:template match="Property[@Name='age']" mode="copy">
<age><xsl:apply-templates mode="copy"/></age>
</xsl:template>

<xsl:template match="Property[@Name='color']" mode="copy">
<colorAttr><xsl:apply-templates mode="copy"/></colorAttr>
</xsl:template>

<xsl:template match="Property[@Name='color']/Property" mode="copy">
<attrColor>
<xsl:attribute name="colName">color</xsl:attribute>
<xsl:apply-templates mode="copy"/>
</attrColor>
</xsl:template>

<!-- Deep copy template -->
<xsl:template match="*|text()|@*" mode="copy">
<xsl:copy>
<xsl:apply-templates mode="copy" select="@*"/>
<xsl:apply-templates mode="copy"/>
</xsl:copy>
</xsl:template>
<!-- Handle default matching -->
<xsl:template match="*"/>
</xsl:stylesheet>
Best Regards,
Octavian
Octavian Nadolu
<oXygen/> XML Editor
http://www.oxygenxml.com
Post Reply