2012-08-02 61 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