noitib
noitib

Reputation: 159

Transform several XML elements, identified by their attributes, into a complex one

I am quite new to XSLT so I could be missing something really obvious.

I have a source XML in this format:

Source:

<?xml version="1.0" encoding="UTF-8"?>
<variables id="simulation">
    <variable id="Code">75</variable>
    <variable id="Type">Varial</variable>
    <variable id="owner">Jeremy</variable>
</variables>

I want to process it in order to look like this:

<Envelope>
    <Code>75</Code>
    <Type>Varial</Type>
    <Owner>Jeremy</Owner>
</Envelope>

I tried using xsl:variable to hold the value of

<xsl:variable
select="<xsl:template match="variable[@id='Code']" name="varcode">">
</xsl:variable>

Using online tools to validate and test the XSLT I have not succeeded in my task.

This is my XSLT so far that is able to grab the value of the first element:

<xsl:template match="variable[@id='Code']" name="varcode">
<Envelope>
    <Code><xsl:value-of select="."/></Code>
    <Type></Type>
    <Owner></Owner>
</Envelope>
</xsl:template>
</xsl:stylesheet>

Can anyone help me getting the values of the remaining ones? Thanks

Upvotes: 0

Views: 27

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167696

Write two templates

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

<xsl:template match="variable[@id]">
    <xsl:element name="{@id}">
        <xsl:value-of select="."/>
    </xsl:element>
</xsl:template>

and you can handle that task in a simple but generic manner.

Upvotes: 1

Pankaj Jaju
Pankaj Jaju

Reputation: 5471

Try this simple xslt

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

    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="variables[@id='simulation']">
        <Envelope>
            <Code>
                <xsl:value-of select="variable[@id='Code']" />
            </Code>
            <Type>
                <xsl:value-of select="variable[@id='Type']" />
            </Type>
            <Owner>
                <xsl:value-of select="variable[@id='owner']" />
            </Owner>
        </Envelope>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 2

Related Questions