2013-07-09 53 views
0

在某些輸出中,我們有一些不需要的嵌套標記。什麼可以最簡單的方式xsl'em走了?使用xslt去除不需要的嵌套元素

源 - 實施例:

<body> 
    <bo> 
      <bo>some text</bo> 
      <bo> 
       <bo>some other text</bo> 
      </bo> 
      <bo>more text</bo> 
    </bo> 
    <bo> 
     <fig/> 
    <bo/> 
</body> 

結果實施例:

<body> 
    <p>some text</p> 
    <p>some other text</p> 
    <p>more text</p> 
    <p> 
     <fig/ 
    <p> 
</body> 

感謝名單中高級。

回答

2

採取以下作爲一種方法的基礎上:

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
</xsl:template> 


<xsl:template match="bo[.//bo]"> 
    <xsl:apply-templates/> 
</xsl:template> 

<xsl:template match="boo[not(boo)]"> 
    <p> 
    <xsl:apply-templates/> 
    </p> 
</xsl:template> 

如果不足夠,那麼你需要在其中輸入變種,你可以有你如何希望他們轉變更詳細的解釋。

使用上述模板的完整的樣式表是

<xsl:stylesheet 
    version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:output indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
</xsl:template> 


<xsl:template match="bo[.//bo]"> 
    <xsl:apply-templates/> 
</xsl:template> 

<xsl:template match="boo[not(boo)]"> 
    <p> 
    <xsl:apply-templates/> 
    </p> 
</xsl:template> 

</xsl:stylesheet> 

和轉換

<body> 
    <bo> 
      <bo>some text</bo> 
      <bo> 
       <bo>some other text</bo> 
      </bo> 
      <bo>more text</bo> 
    </bo> 
    <bo> 
     <fig/> 
    </bo> 
</body> 

<body> 
    <bo>some text</bo> 
    <bo>some other text</bo> 
    <bo>more text</bo> 
    <bo> 
     <fig/> 
    </bo> 
</body> 
0

的一般解省略直接相互嵌套相同標籤:

<stylesheet version="2.0" xmlns="http://www.w3.org/1999/XSL/Transform"> 

    <template match="*[name(..)=name()]"> 
     <apply-templates/> 
    </template> 

    <template match="@* | node()"> 
     <copy> 
      <apply-templates select="@* | node()"/> 
     </copy> 
    </template> 

</stylesheet> 

英文:「通過複製每個節點,除非它的名字與其父母相同;在這種情況下,只需複製孩子「

+0

這感覺是錯誤的方式;在這個例子中,它是被放棄的父元素,而不是孩子。 –