Link to home
Start Free TrialLog in
Avatar of jaypi
jaypi

asked on

XSLT: Transforming a leaf node

Hi,
I'm new on XSL an XPATH, I'm trying to create an xsl tranformation to do that:

XML to transform

<test id="a">
<leaf attribute="1">some text</leaf>
</test>

Result Wanted:
<test id="a">
<leaf>
<attribute>1</attribute>
<leaf> some text</leaf>
</leaf>
</test>

The XSL transformation:

If a tag (element) has an attribute, and text value:
Example: <leaf attribute="1">some text</leaf>

convert the attribute to an element, and add a child node with the same name as the element:
<leaf>
<attribute>1</attribute> // attribute converted to an element
<leaf> some text</leaf> // a new sub-element with the same name as the containing element
</leaf>

But if a tag with an attribute has no text-element:
Example: the "test" element
<test id="a">
<leaf>
...
</leaf>
</test>

Do nothing.
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

This should get you started
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="*[string-length(normalize-space(text())) > 0]">
        <xsl:copy>
            <xsl:for-each select="@*">
                <xsl:element name="{name()}">
                    <xsl:value-of select="."/>
                </xsl:element>
            </xsl:for-each>
            <xsl:element name="{name()}">
                <xsl:apply-templates select="node()"/>
            </xsl:element>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*[string-length(normalize-space(text())) = 0]">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Open in new window

Avatar of jaypi
jaypi

ASKER

Thanks Gertone, but this is not the result expect:

Input XML:

<test>blabla</test>

Result:

<test><test>blabla</test></test>

Result expected:

<test>blabla</test>

Here the "test" tag doesn't have any attribute, so It should remain the same.
ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jaypi

ASKER

Thanks Flash Gordon/Gertone for your very quick and excellent answer :D