2017-10-16 421 views
0

我遇到以下問題。 我有這樣通過XSLT和空元素刪除XML中的空標記

<p> 
    <span class="dateline">City</span><p> 
     <p> 
      <em>City.</em>some text 
     </p> 
    </p><p> 
     <p/> 
    </p> 
    [... unknown number of other nested paragraphs with text ...] 
</p> 

一個XML文件,我希望它看起來像:

<p> 
    <span class="dateline">City</span> 
    <em>City.</em>some text 
</p> 

所以我必須去到每片葉子對標籤,並採取一切並且只要有父p標籤,就將其移動到父p標籤。 然後我會刪除所有空的p標籤。

這怎麼能用xslt 1.0來完成?

+0

除了手動編輯,你有什麼嘗試?請發佈代碼。 – lit

+0

歡迎使用堆棧溢出。如果你展示了你所嘗試過的東西,那麼你很可能會對這些問題做出很好的回答,並以允許其他人重現問題的形式出現(如果你不知道從哪裏開始,這當然很難)。不顯示你的工作會給人留下你沒有做過的印象,只希望別人爲你做你的工作。在[SO幫助文件](http://stackoverflow.com/help/how-to-ask)以及Eric Raymond和Rick Moen的文章[如何以智能的方式提問]中提供有效問題的建議很好( http://catb.org/~esr/faqs/smart-questions.html)。 –

回答

1

我會寫一個身份轉換(如果你不知道那是什麼,看看它,因爲它是值得學習),然後添加兩個模板的段落:一個match="p"匹配未嵌套p元素其他p元素,以及match="p[ancestor::p]"與其他人匹配。第一個模板只是對標識模板的明確重述(也就是說,模板可以在不改變功能的情況下被省略;我只會將其包括在內以便明確處理所有段落)。第二個省略了xsl:copy指令,只是將模板應用於所有的孩子。

+0

教學完善。 – kjhughes

0
<!-- This template preserve all elements without template --> 

<xsl:template match="*"> 
    <xsl:copy> 
     <xsl:copy-of select="@*"/> 
     <xsl:apply-templates /> 
    </xsl:copy> 
</xsl:template> 


<!-- This template remove all elements without childs (you can replace * by p)--> 
<xsl:template match="*[not(node())]"/> 
<!-- This template remove p inside other p but preserve all childs --> 
<xsl:template match="p[parent::p]"> 
    <xsl:apply-templates /> 
</xsl:template>