Reputation: 57
The sample xml file is shown below
<a>
<apple color="red"/>
<banana color="yellow"/>
<sugar taste="sweet"/>
<cat size="small"/>
</a>
What should I write in XSLT so that i can get the sample output below ?
<AAA>apple</AAA>
<BBB>color</BBB>
<CCC>red</CCC>
<AAA>banana</AAA>
<BBB>color</BBB>
<CCC>yellow</CCC>
Below is the XSLT file i wrote but I don't know how to extract the value.
<xsl:template match="*/*">
<AAA>
<xsl:value-of select="name()"/>
</AAA>
<xsl:apply-templates select="@*"/>
</xsl:template>
<xsl:template match="@*">
<BBB>
<xsl:value-of select="name()"/>
</BBB>
</xsl:template>
Upvotes: 2
Views: 259
Reputation: 243459
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*/*[not(self::sugar or self::cat)]">
<AAA><xsl:value-of select="name()"/></AAA>
<BBB><xsl:value-of select="name(@*)"/></BBB>
<CCC><xsl:value-of select="@*"/></CCC>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<a>
<apple color="red"/>
<banana color="yellow"/>
<sugar taste="sweet"/>
<cat size="small"/>
</a>
produces the wanted, correct result:
<AAA>apple</AAA>
<BBB>color</BBB>
<CCC>red</CCC>
<AAA>banana</AAA>
<BBB>color</BBB>
<CCC>yellow</CCC>
Note: The assumption is made, that each matched element has only a single attribute, which is the case with the provided XML document.
Upvotes: 1
Reputation: 260
your xml should be as
<catalog>
<fruit>
<name>apple </name>
<color>red</color>
</fruit>
<fruit>
<name>banana </name>
<color>yellow</color>
</fruit>
</catalog>
XSLT as:
<xsl:for-each select="catalog/fruit">
<tr>
<td><AAA><xsl:value-of select="title"/></AAA></td>
<td><BBB>color</BBB></td>
<td><CCC><xsl:value-of select="color"/></CCC></td>
</tr>
</xsl:for-each>
Upvotes: 2
Reputation: 15264
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="apple">
<AAA><xsl:value-of select="local-name()"/></AAA>
</xsl:template><!-- and then more of that for banana etc -->
<xsl:template match="@*|node()"><!-- copy template -->
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
And so on for banana
etc. If you don't know the copy (or identity) template idiom then go googling for it; without it your XSLT life will be miserable.
Upvotes: 1