2013-05-21 64 views
3

我需要一些幫助這個XML文檔轉換:刪除XML標記之間的某些文本

<root> 
<tree> 
<leaf>Hello</leaf> 
ignore me 
<pear>World</pear> 
</tree> 
</root> 

這樣:

<root> 
<tree> 
<leaf>Hello</leaf> 
<pear>World</pear> 
</tree> 
</root> 

的例子被簡化,但基本上,我既可以刪除所有實例「不理我」或不在葉子或梨內的一切。

我只有想出這個XSLT那份幾乎一切:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:output method="xml" encoding="UTF-8" standalone="yes"/> 

    <xsl:template match="root|tree"> 
     <xsl:element name="{name()}"> 
      <xsl:copy-of select="@*"/> 
      <xsl:apply-templates/> 
     </xsl:element> 
    </xsl:template> 

    <xsl:template match="leaf|pear"> 
     <xsl:element name="{name()}"> 
      <xsl:copy-of select="child::node()"/> 
     </xsl:element> 
    </xsl:template> 

</xsl:stylesheet> 

什麼我發現是如何使用xsl:調用模板爲去除葉或梨文字元素,但這並不適用於元素中的內容。

在此先感謝。

回答

4

看起來像一個身份變換是你正在尋找。 因爲作爲根或樹的直接孩子的文本應該被忽略,爲此添加空模板。 因此嘗試:

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

    <xsl:output indent="yes" method="xml" encoding="utf-8" omit-xml-declaration="yes" /> 

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

</xsl:stylesheet> 

這將產生以下輸出:

<root> 
    <tree> 
    <leaf>Hello</leaf> 
    <pear>World</pear> 
    </tree> 
</root> 
+0

接受簡單。根據具體情況,它們都是非常好的答案。 –

2

這裏的另一個選項,將刪除混合內容的任何元素文本(包括元素和文本)...

XML輸入

<root> 
    <tree> 
     <leaf>Hello</leaf> 
     ignore me 
     <pear>World</pear> 
    </tree> 
</root> 

XSLT 1.0

<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="*[* and text()]"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|*"/> 
     </xsl:copy>  
    </xsl:template> 

</xsl:stylesheet> 

XML輸出

<root> 
    <tree> 
     <leaf>Hello</leaf> 
     <pear>World</pear> 
    </tree> 
</root> 

而且,如果真的文本只有ignore me,你可以這樣做:

<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="text()[normalize-space(.)='ignore me']"/> 

</xsl:stylesheet> 
相關問題