2010-09-27 27 views
1

我的源文件看起來像這樣:XSLT,如何選擇標籤,基於另一個同級別標記的內容

<stuff> 
<s> 
    <contents> 
     <code>503886</code> 
     <code>602806</code> 
    </contents> 
    ... 
</s> 
<p> 
    <code>344196</code> 
    <export>true</export> 
    ... 
</p> 
<!-- more 's' and 'p' tags --> 
... 
</stuff> 

我需要遍歷「S」,並選擇那些 - 這裏面「內容」標籤有一個屬於'p'的'代碼',該代碼具有export = true。

我一直在試圖解決這個在過去的幾個小時。 請分享一些想法。

+0

問得好(+1)。查看我的答案以獲取單行XPath解決方案。 :) – 2010-09-27 16:40:01

回答

1

這個樣式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:key name="kSByCode" match="s" use="contents/code"/> 
    <xsl:template match="text()"/> 
    <xsl:template match="p[export='true']"> 
     <xsl:copy-of select="key('kSByCode',code)"/> 
    </xsl:template> 
</xsl:stylesheet> 

有了這個輸入:

<stuff> 
    <s> 
     <contents> 
      <code>503886</code> 
      <code>602806</code> 
     </contents> 
    </s> 
    <p> 
     <code>602806</code> 
     <export>true</export> 
    </p> 
</stuff> 

輸出:

<s> 
    <contents> 
     <code>503886</code> 
     <code>602806</code> 
    </contents> 
</s> 

注意:每當有交叉引用,使用的密鑰。

編輯:錯過了s部分的迭代。謝謝,Dimitre!

編輯2:重讀這個答案我看到它可能會令人困惑。因此,對於表達選擇節點,使用:

key('kSByCode',/stuff/p[export='true']/code) 
0

我需要遍歷「S」,並選擇 那些 - 這裏面「內容」標籤 有一個「代碼」屬於具有export = true的'p' 。

使用

<xsl:apply-templates select= 
"/*/s 
     [code 
     = 
     /*/p 
      [export='true'] 
         /code]"/> 
+0

+1我錯過了*遍歷's' *部分。我編輯了我的答案。 – 2010-09-27 16:51:30

相關問題