Search code examples
xsltxslt-2.0soaxslt-groupingoracle-soa

Mapping an XML Element value to array of elements in target XML


I have a requirement where I have an XML File like:

<main>
    <Qnumber>10</Qnumber>
    <Qaddress>hyderabad</Qaddress>
    <Qratio>12:3</Qratio>
    <QGet>Getthevalue</QGet>
</main>

These values are to be mapped to target schema in the following fashion:

We have a tag called which is of 1to many(1-infinite):

<Additional properties>
    <property>
        <Name></Name>
        <Value></Value>
    </property>
</Additional properties>

Now I have to map to this in the following way:

<Additional properties>
    <property>
        <Name>Qnumber</Name>
        <Value>10</Value>
    </property>
    <property>
        <Name>Qaddress</Name>
        <Value>hyderabad</Value>
    </property>
    <property>
        <Name>Qratio</Name>
        <Value>12:3</Value>
    </property>
    <property>
        <Name>QGet</Name>
        <Value>Getthevalue</Value>
    </property>
</Additional properties>

I have to this stuff in the XSLT.Can anyone help on this particular concept. Thanks


Solution

  • First, you cannot have space in the name of your XML element. Thus, I have replaced the space with _ .

    Here is a solution:

    <?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" />
    
        <xsl:template match="main">
            <Additional_properties>
                <xsl:for-each select="./*">
                    <xsl:if test="position() &lt; 5">
                        <property>
                            <xsl:element name="Name">
                                <xsl:value-of select="name()"/>
                            </xsl:element>
                            <xsl:element name="Value">
                                <xsl:value-of select="text()"/>
                            </xsl:element> 
                        </property>
                    </xsl:if>
                </xsl:for-each> 
            </Additional_properties>
        </xsl:template>
    </xsl:stylesheet>