How can I convert this XML
开发者_如何转开发<albums>
<album title="New Zealand">
<album title="Auckland">
<image title="Mt Eden railroad station"/>
<image title="Morgan St"/>
</album>
</album>
<album title="Russia">
<image title="Capital of Siberia"/>
</album>
</albums>
into that
<div class="level-0">
New Zealand
Russia
</div>
<div class="level-1">
Auckland
</div>
<div class="level-1">
<img alt="Capital of Siberia"/>
</div>
<div class="level-2">
<img alt="Mt Eden railroad station"/>
<img alt="Morgan St"/>
</div>
?
It's difficult to tell exactly what you're trying to do from this sample, but generally, you can flatten an XML tree with a slight modification to the identity template:
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@*"/>
</xsl:copy>
<xsl:apply-templates select="node()" />
</xsl:template>
You can probably adapt this to your specific needs.
<xsl:template match="/">
<xsl:apply-templates select="/albums | //album"/>
</xsl:template>
<xsl:template match="albums | album">
<div class="level-{count(ancestor-or-self::album)}">
<xsl:apply-templates select="album/@title | image"/>
</div>
</xsl:template>
<xsl:template match="album/@title">
<xsl:value-of select="concat(.,'
')"/>
</xsl:template>
<xsl:template match="image">
<img alt="{@title}"/>
</xsl:template>
精彩评论