Inverting data and attribute using XSLT
Using XSLT I want to tranform this XML:
<exchangeRates>
<rate country="aud">0.97</rate>
</exchangeRates>
into this XML:
<xchgRates>
<entry开发者_开发百科 xrate="0.97">aud</entry>
</xchgRates>
EDIT: exchangeRates needs to become xchgRates. Changed xRate to xrate to match correct solution.
Thanks for all your help guys!
I haven't tried this but something like this should work:
<xsl:template match="exchangeRates/rate">
<entry>
<xsl:attribute name="xRate"><xsl:value-of select="." /></xsl:attribute>
<xsl:value-of select="@country" />
</entry>
</xsl:template>
A complete and short solution:
<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="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="exchangeRates">
<xchgRates>
<xsl:apply-templates select="node()|@*"/>
</xchgRates>
</xsl:template>
<xsl:template match="rate">
<entry xrate="{.}">
<xsl:value-of select="@country"/>
</entry>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided XML document:
<exchangeRates>
<rate country="aud">0.97</rate>
</exchangeRates>
the wanted, correct result is produced:
<xchgRates>
<entry xrate="0.97">aud</entry>
</xchgRates>
Explanation:
Using and overriding the identity rule/template
Using AVT (Attribute-Value-Templates) is recommended as it needs less typing and results in shorter, more understandable and maintainable code.
Almost all attributes of the XSLT instructions with a few exceptions (notably the select
attribute) allow AVTs.
精彩评论