XSL apply-templates output issues

扶醉桌前 提交于 2019-12-12 03:34:27

问题


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, ...


回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/30764727/xsl-apply-templates-output-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!