2014-04-28 80 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