XSLT忽略子元素的模板

时间:2014-04-28 15:43:47

标签: xml xslt nodes

我正在尝试使用XSLT将HTML转换为XML:

HTML:

<html>
<body>
    <p class="one">Some paragraph 1.</p>
    <p class="one">Some paragraph 2.</p>
    <p class="one">Some paragraph 3  with <em>em</em>.</p>
    <p class="one">Some paragraph 4.</p>
    <p class="one">Some paragraph 5.</p>
    <h3>Some heading</h3>
    <p class="two">Some other paragraph 1 with <em>em</em>.</p>
    <p class="two">Some other paragraph 2.</p>
    <p class="two">Some other paragraph 3.</p>
    <p class="two">Some other paragraph 4.</p>
    <p class="two">Some other paragraph 5.</p>
</body>
</html>

期望的输出:

Some paragraph 1.
Some paragraph 2.
Some paragraph 3  with <emphasis>em</emphasis>.
Some paragraph 4.
Some paragraph 5.
Some heading
<paragraph>Some other paragraph 1 with <emphasis>em</emphasis>.</paragraph>
<paragraph>Some other paragraph 2.</paragraph>
<paragraph>Some other paragraph 3.</paragraph>
<paragraph>Some other paragraph 4.</paragraph>
<paragraph>Some other paragraph 5.</paragraph>

XSLT:

<xsl:output indent="yes" />


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

<xsl:template match="em">
    <emphasis><xsl:value-of select="."/></emphasis>
</xsl:template> 

<xsl:template match="p[@class='two']">
    <paragraph><xsl:value-of select="."/></paragraph>
</xsl:template> 

此XSLT转换的输出:

Some paragraph 1.
Some paragraph 2.
Some paragraph 3  with <emphasis>em</emphasis>.
Some paragraph 4.
Some paragraph 5.
Some heading
<paragraph>Some other paragraph 1 with em.</paragraph>
<paragraph>Some other paragraph 2.</paragraph>
<paragraph>Some other paragraph 3.</paragraph>
<paragraph>Some other paragraph 4.</paragraph>
<paragraph>Some other paragraph 5.</paragraph>

em元素的模板似乎在没有为父元素(p.one)定义其他模板时正常工作。但是,当父元素(p.two)存在模板时,子元素(em)元素的模板似乎被转换忽略而不是获取:

<paragraph>Some other paragraph 1 with <emphasis>em</emphasis>.</paragraph>

我明白了:

<paragraph>Some other paragraph 1 with em.</paragraph>

在这种情况下,为什么XSLT会忽略em元素的模板?

1 个答案:

答案 0 :(得分:1)

它被忽略了,因为你只是用以下内容打印出来的值:

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

如果您希望将em模板应用于p[@class='two']模板的内容,则应将其替换为:

<xsl:template match="p[@class='two']">
    <paragraph><xsl:apply-templates /></paragraph>
</xsl:template> 

现在<paragraph>的内容将在模板中处理(如果有的话)(不是简单地转换成文本并打印出来)。