2012-08-02 62 views
1

这是我的XML输入:查询在XSLT路径

<maindocument> 
<first> 
<testing>random text</testing> 
<checking>random test</checking> 
</first> 
<testing unit = "yes"> 
<tested>sample</tested> 
<checking>welcome</checking> 
<import task="yes"> 
<downloading>sampledata</downloading> 
</import> 
<import section="yes"> 
<downloading>valuable text</downloading> 
</import> 
<import chapter="yes"> 
<downloading>checkeddata</downloading> 
</import> 
</testing> 
</maindocument> 

输出应该是:第一,它会检查是否将测试单元=“是”。如果是,则必须检查section属性=“是”。这是输出:

<maindocument> 
<import> 
     <doctype>Valuable text</doctype> 
</import> 
</maindocument 

我在用xsl:if条件检查。首先,它将检查测试单元是否为“是”。然后它会检查导入部分是否为“是”。该代码无法实现上述输出。

+0

你使用什么查询? – 2012-08-02 20:32:55

+0

如果测试单位=“否”,或者如果导入部分=“否”,您希望发生什么? – 2012-08-02 21:22:47

回答

2

这是你在找什么?

XSLT 2.0

<xsl:stylesheet version="2.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="maindocument"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|testing[@unit='yes']/import[@section='yes']"/>   
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="import/@*"/> 

</xsl:stylesheet> 

输出

<maindocument> 
    <import> 
     <downloading>valuable text</downloading> 
    </import> 
</maindocument> 

如果你不想让任何属性在<maindocument>,从select删除@*|xsl:apply-templates(在maindocument模板)。

1

这种转变

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output omit-xml-declaration="yes" indent="yes"/> 

    <xsl:template match="/*"> 
     <maindocument> 
     <xsl:apply-templates select="testing[@unit='yes']/import[@section='yes']"/> 
     </maindocument> 
    </xsl:template> 

    <xsl:template match="import"> 
     <import> 
     <doctype><xsl:value-of select="*"/></doctype> 
     </import> 
    </xsl:template> 
</xsl:stylesheet> 

时所提供的XML文档应用:

<maindocument> 
    <first> 
     <testing>random text</testing> 
     <checking>random test</checking> 
    </first> 
    <testing unit = "yes"> 
     <tested>sample</tested> 
     <checking>welcome</checking> 
     <import task="yes"> 
      <downloading>sampledata</downloading> 
     </import> 
     <import section="yes"> 
      <downloading>valuable text</downloading> 
     </import> 
     <import chapter="yes"> 
      <downloading>checkeddata</downloading> 
     </import> 
    </testing> 
</maindocument> 

产生想要的,正确的结果:

<maindocument> 
    <import> 
     <doctype>valuable text</doctype> 
    </import> 
</maindocument> 
+0

好答案(+1)。但是请注意,OP的期望输出似乎有一个“”元素,而不是“”。不知道这是一个错误还是故意... – ABach 2012-08-04 19:59:41

+0

@ABach,感谢您注意到这一点 - 没有什么大不了的 - 纠正 - 完成。 – 2012-08-04 20:41:48

+0

出于好奇:你为什么用''而不是''?在这种情况下你的版本更高效吗? – ABach 2012-08-04 21:00:17