Maxim Tkachenko
Maxim Tkachenko

Reputation: 5808

XSLT: show elements by their order

In source xml I have element <ad> and its content may be like this:

<ad>
    <content>fdsdf</content>
    <title>gfdgdg</title>
</ad>

or like this

<ad>
    <content><title>gfdgdg</title></content>
    <title>gfdgdg</title>
    <content>fdsdf</content>
</ad>

So I need to render elements not using hard-coded order like

<xsl:apply-templates select="title"...">
etc. 

but render them by their order and nesting. How to do this?

Upvotes: 1

Views: 62

Answers (1)

Tim C
Tim C

Reputation: 70638

This is actually quite straight-forward in XSLT, as you can make use of its built-in templates which will iterate over the nodes in the document in the order they appear in the document.

All you need to do is write matching templates for the elements you wish to transform.

Try this XSLT

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

    <xsl:template match="title">
        <h3>
            <xsl:apply-templates select="@*|node()"/>
        </h3>
    </xsl:template>

    <xsl:template match="content">
        <div>
            <xsl:apply-templates select="@*|node()"/>
        </div>
    </xsl:template>
</xsl:stylesheet>

Note that if your XML has nodes for which you have no matching template in the XSLT, the built-in template will not output that node, but will continue processing its children until it either finds a matching template, or a text node, in which case it will output the text on its own.

When applied to this XML

<ad><content>fdsdf</content><title>gfdgdg</title></ad>

The output is as follows:

<div>fdsdf</div>
<h3>gfdgdg</h3>

When applied to this XML

<ad><content><title>gfdgdg</title></content><title>gfdgdg</title><content>fdsdf</content></ad>

The output is as follows:

<div>
   <h3>gfdgdg</h3>
</div>
<h3>gfdgdg</h3>
<div>fdsdf</div>

Upvotes: 2

Related Questions