XSLT:仅显示具有属性的文本

时间:2017-08-31 01:23:14

标签: xml xslt

我有以下XML:

<text>
    <sentence type="grocery">I bought <fruit> apples</fruit> at the grocery store.</sentence>
    <sentence type="grocery">I also bought <fruit> bananas</fruit> at the store.</sentence>
    <sentence>Then, I bought a basket at another store.</sentence>
</text>

我当前的xslt看起来像这样(非常感谢michael.hor257k):

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

    <xsl:template match="/text">
        <html>
            <body>
                <xsl:apply-templates select="sentence"/>
            </body>
        </html>
    </xsl:template>

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

    <xsl:template match="fruit"> 
         <span style="color:red;"> 
             <xsl:apply-templates/>
         </span> 
    </xsl:template>

</xsl:stylesheet>

但是,我需要输出如下例(仅针对特定属性<sentence type="grocery">):

<html>
    <body>
        <p>I bought <span style="color:red;"> apples</span> at the grocery store.</p>
        <p>I also bought <span style="color:red;"> bananas</span> at the story.</p>
    </body>
</html>

请帮助使用XSLT。感谢。

1 个答案:

答案 0 :(得分:0)

你应该使用

<xsl:apply-templates select="sentence[@type='grocery']"/>

而不是

<xsl:apply-templates select="sentence"/>

删除所有没有属性值“杂货”的“type”属性的句子。