2011-08-28 116 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文档:''并且看到顶层节点*是*输出 - 但它不应该。 –