XSL apply-templates output issues

159 Views Asked by At

Given this XML:

<?xml version="1.0" encoding="iso-8859-2" ?>
    <products>
        <p>
            <id> 50 </id>
            <name> Murphy </name>
            <price> 33 </price>
        </p>
        <p>
            <id> 40 </id>
            <name> Eddie </name>
            <price> 9999 </price>
        </p>
        <p>
            <id> 20 </id>
            <name> Honey </name>
            <price> 9999 </price>
        </p>
        <p>
            <id> 30 </id>
            <name> Koney </name>
            <price> 11 </price>
        </p>
        <p>
            <id> 10 </id>
            <name> Margarethe </name>
            <price> 11 </price>
        </p>
    </products>

With this XSL:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="p[id &gt; 20]">
    <idKP>   <xsl:value-of select="id"/></idKP>
    <skitter><xsl:value-of select="name"/></skitter>
</xsl:template>


<xsl:template match="/">
    <xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>

Having this output:

<?xml version="1.0"?>
<idKP>50</idKP><skitter>Murphy</skitter>
<idKP>40</idKP><skitter>Eddie</skitter>
20
Honey
9999
<idKP>30</idKP><skitter>Koney</skitter>
10
Margarethe
11

Q : Why there are values of those who did not matched? 20, Honey, 9999, ...

2

There are 2 best solutions below

2
On BEST ANSWER

Because of the built-in template rules - when there are no explicit templates to match a particular node, the built-in rules are used, which for element nodes means <xsl:apply-templates/> and for text nodes means <xsl:value-of select="."/>. The effect of these two rules in combination is to output all the text under the elements but not the element tags themselves.

You could add a second do-nothing template

<xsl:template match="p" />

to completely ignore p elements that don't match your condition. An explicit template, even a do-nothing one, is preferred over the default built-in rule.

0
On

To add to the answer, this is the solution:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="p[id &gt; 20]">
    <idKP>   <xsl:value-of select="id"/></idKP>
    <skitter><xsl:value-of select="name"/></skitter>
</xsl:template>

<xsl:template match="p"/>

</xsl:stylesheet>