2

我是 XSL 的新手,这很明显,一些非常基本的东西让我很困惑。假设我有一个如下所示的 XML 文档:

<?xml version="1.0" encoding="UTF-8"?>
<essay><author>John Stamos</author>
<text>
    <p>In his song "Turn! Turn! Turn!," Bob Dylan quotes the Bible:
    <quotation>"To every thing there is a season, and a time to every purpose under the 
    heaven,"</quotation> which is a well-known quotation from Ecclesiastes.
    </p>
</text>
</essay>

对于我目前的目的,我想标记元素中的文本<p>以及<quotation>元素并只打印这些。IE,我想要输出

    <span id="paragraph">In his song "Turn! Turn! Turn!," Bob Dylan quotes the Bible:
    <span id="quotation">"To every thing there is a season, and a time to every purpose under the 
    heaven,"</span> which is a well-known quotation from Ecclesiastes.</span>

但是,当我使用如下样式表时,我遇到了麻烦:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:tei="http://www.tei-    
c.org/ns/1.0"
version="1.0">

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

<xsl:template match="p">
    <span id="paragraph"><xsl:value-of select="//p"/></span>
</xsl:template>

<xsl:template match="quotation">
    <span id="quotation"><xsl:value-of select="//quotation"/></span>
</xsl:template>

</xsl:stylesheet>

报价模板永远不会被调用;p,它的父级,显然优先。我该怎么做呢?

4

1 回答 1

2

引用模板永远不会被调用的原因是您没有告诉 XSLT 在模板匹配p中继续处理。您所做的只是输出一个元素,因此 XSLT 处理器不会继续为p元素的任何后代进行任何模板匹配。您需要做的是将此行添加到模板中(在span元素内),以便 XSLT 可以继续并匹配引号元素。

<xsl:apply-templates />

其实你这行也有问题

<xsl:value-of select="//p"/>

这实际上将返回文档中第一个p元素下的所有文本,不一定是您所在的那个。你可以把它改成这样:

 <xsl:value-of select="."/>

但这将包括嵌套引用元素中的任何文本。但是,在这种情况下,您实际上根本不需要这个xsl:value-of,因为 XSLT 具有内置模板的概念,它将输出它找到的任何文本节点的文本,因此只需执行xsl: apply-templates会处理这个问题。

试试这个 XSLT

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

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

<xsl:template match="p">
    <span id="paragraph"><xsl:apply-templates /></span>
</xsl:template>

<xsl:template match="quotation">
    <span id="quotation"><xsl:apply-templates /></span>
</xsl:template>

</xsl:stylesheet>
于 2013-09-04T22:53:29.830 回答