2014-04-28 83 views
1

我试图使用XSLT转换HTML到XML:XSLT忽略的子元素模板

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

它越来越被忽略,因为你只是用打印出的值:

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

如果你想在p[@class='two']模板的内容将被应用的em模板,那么你应该将其替换为

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

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

+0

谢谢,这是有效的。由于em元素在很多其他元素中使用,是否有任何方法可以使em模板在每个其他模板中都不使用apply-templates的情况下工作? – Rafal

+1

如果模板未调用任何其他模板,则模板处理在此处结束。当然,如果你有非常相似的情况,你可以使用通用模板(带有“match =”*“')。您还可以使用''来选择要处理的模板 – helderdarocha