Skip to Content
0
Jan 29, 2013 at 12:59 AM

two xslt questions

89 Views

Hi Gurus

i am starting to learn xslt mapping and the xslt language. here i have two questions on it:

1. if there are multiple "<xsl:template match=" in a program, how are they processed? what i was told was the second template will override the first one. however when i changed the sequence of template in stylus studio, the result was the same. for example:

the source xml is:

<country xmlns="http://india.com/states" version="1.0">

<state>

<city>

<name>

<namefirst>XU</namefirst>

</name>

<name1>Sandy</name1>

</city>

</state>

<state2>

<city2>

<name2>MUMBAI</name2>

</city2>

</state2>

</country>

while this is the first version of the xslt :

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:x="http://india.com/states">

<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="*">

<xsl:element name="{name()}">

<xsl:apply-templates/>

</xsl:element>

</xsl:template>

<xsl:template match="*[ancestor-or-self::x:city]">

<xsl:apply-templates/>

</xsl:template>

</xsl:stylesheet>

from my understanding, the first template will copy all the element nodes of the source, while the second one will erase any nodes who have CITY as one of the ancestor nodes or who is CITY node itself. This part will override the same segment from the first template.

the result is:

<country>

<state>

XU

Sandy

</state>

<state2>

<city2>

<name2>MUMBAI</name2>

</city2>

</state2>

</country>

however when the sequence has been changed like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:x="http://india.com/states">

<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="*[ancestor-or-self::x:city]">

<xsl:apply-templates/>

</xsl:template>

<xsl:template match="*">

<xsl:element name="{name()}">

<xsl:apply-templates/>

</xsl:element>

</xsl:template>

</xsl:stylesheet>

the result is the same. if the second template will override the first one, the result of this one should be the copy of ALL nodes from the source xml, because the erased nodes in the first template here has been copied by the second template here.

if it is not the override simply what is the working process behind?

2. just to confirm that

<xsl:template match="*[ancestor-or-self::x:city]"> will get all the nodes who has an 'city' node as one of the ancestor element or the 'city' node itself. it does not match any node who is the ancestor of 'city' node or the 'city' node itself.

one of the evidences is when the following code was run in stylus studio:

<xsl:template match="*[ancestor-or-self::x:city]">

<xsl:element name="{name()}">

<xsl:apply-templates/>

</xsl:element>

</xsl:template>

just the nodes from 'city' and below were chosen:

<city>

<name>

<namefirst>XU</namefirst>

</name>

<name1>Sandy</name1>

</city>

thanks