XSLT apply-template不显示相同标记的多个

时间:2014-11-07 13:57:31

标签: html xml xslt xhtml xslt-2.0

我正在使用XSLT样式表将Alice in Wonderland的文本的简单XML文件呈现为HTML。

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Alice.xsl"?>


<book>
<title>Alice's Adventures in Wonderland</title>

<text>
<chapter>
<chapter_heading>Chapter I. Down the Rabbit-Hole</chapter_heading>

<p>Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'</p>

<p>So she was considering in her own mind (as well as she could, for the
hot day made her feel very sleepy and stupid), whether the pleasure
of making a daisy-chain would be worth the trouble of getting up and
picking the daisies, when suddenly a White Rabbit with pink eyes ran
close by her.</p>
</chapter>

</text>
</book>

简单的东西。我们试图使用以下代码将章节的标题和段落输出到HTML中的标记:

<?xml version="1.0" encoding="UTF-8"?><!-- DWXMLSource="http://www.w3.org/1999/XSL/Transform" -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8"/>

<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

</head>

<body>

<article>
    <xsl:apply-templates/>
</article>

</body>


</html>
</xsl:template>

<xsl:template match="title"/>

<xsl:template match="chapter">
    <h3>
      <xsl:apply-templates select="chapter_heading"/>
    </h3>
    <div class="paragraph">
        <xsl:apply-templates select="p"/>
    </div>
</xsl:template>


</xsl:stylesheet>

但是,一旦在浏览器中打开XML文件,XML中的所有单独的“p”标记就会被组合成HTML中的一个大“div”。

我们的团队显然对XSL来说是一个新手,但就我们能够进行研究而言,我们并没有说明为什么这不能顺利进行。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您没有为template元素定义<p>。 您使用<p><xsl:apply-templates select="p"/>元素上有效地应用了模板,但没有特定的模板,xslt处理器只应用默认模板,只输出元素的文本内容。这就是为什么你把所有东西都放在同一个<div class='paragraph'>元素中(这是你在<p>上应用模板之前创建的父元素)。

我想,您希望保留输入中的<p>元素,然后只需添加下面的模板声明,您就可以在输出中获得<p>

<xsl:template match="p">
    <xsl:copy-of select="."/>
</xsl:template>

作为一般设计模板,当您想要复制具有某些布局功能的输入时,请使用带有此默认声明的“复制模板模式”,该声明适用于任何输入(<p> <citation>等)。 / p>

<!-- This match will select any element without any other template matching (the `<p>` elements in your case.)-->
<xsl:template match="*">
    <!-- First copy the element itself -->
    <xsl:copy>
       <!-- Then copy the attributes if any. -->
       <xsl:copy-of select="@*">
       <!-- Finally apply-templates on childs, then text nodes will be outputed by default templates, and elements would go through your template flow allowing to be copied or formatted if needed (with specific templates) -->
      <xsl:apply-templates select="node()"/>
    </xsl:copy>
</xsl:template>
相关问题