2011-08-28 113 views
1

我想使用xslt將xml文件轉換爲幾乎相同的xml文件,但會根據屬性剝離節點。如果一個節點有一個屬性,它的子節點並沒有被複制到輸出文件中。例如我想從具有的「not_really」基於屬性的xslt帶節點樹

這是要轉換的XML「健康」的屬性下面的XML文件剝離節點

<diet> 

    <breakfast healthy="very"> 
    <item name="toast" /> 
    <item name="juice" /> 
    </breakfast> 

    <lunch healthy="ofcourse"> 
    <item name="sandwich" /> 
    <item name="apple" /> 
    <item name="chocolate_bar" healthy="not_really" /> 
    <other_info>lunch is great</other_info> 
    </lunch> 

    <afternoon_snack healthy="not_really" > 
    <item name="crisps"/> 
    </afternoon_snack> 

    <some_other_info> 
    <otherInfo>important info</otherInfo> 
    </some_other_info> 
</diet> 

這是所需的輸出

<?xml version="1.0" encoding="utf-8" ?> 

<diet> 

    <breakfast healthy="very"> 
    <item name="toast" /> 
    <item name="juice" /> 
    </breakfast> 

    <lunch healthy="ofcourse"> 
    <item name="sandwich" /> 
    <item name="apple" /> 
    <other_info>lunch is great</other_info> 
    </lunch> 

    <some_other_info> 
    <otherInfo>important info</otherInfo> 
    </some_other_info> 
</diet> 

這是我曾嘗試(不sucess :)

<?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" indent="yes"/> 

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

回答

0

兩個小問題:

  1. not_really應該加引號,表示這是一個文本值。否則,它將評估它尋找名爲「not_really」的元素。
  2. 您的應用程序模板正在選擇節點誰的@healthy值是「not_really」,你想要的是相反的。

應用補丁到你的樣式表:

<?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" indent="yes"/> 

    <xsl:template match="@* | node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@* | node()[not(@healthy='not_really')]"/> 
    </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

或者,你可以只創建一個具有@healthy='not_really'元素空的模板:

<?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" indent="yes"/> 

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

    <xsl:template match="*[@healthy='not_really']"/> 

</xsl:stylesheet> 
+1

這可能是有趣的,知道你的第一個解決方案不正確。試試這個XML文檔:''並且看到頂層節點*是*輸出 - 但它不應該。 –