2010-09-27 53 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

相关问题