2016-09-29 40 views
0

我有了下面的树结构的XML文件:有什么办法在xslt中对非子元素进行分组吗?

<foo attr1=""/> 
<foo2 num="1"/> 
<foo2 num="2"/> 
<foo2 num="3"/> 
<foo2 num="4"/> 
<foo attr1=""/> 
<foo2 num="1"/> 
... 

正如你所看到的元素foo2的是不是foo的子元素,但我想 组foo2的NUM =“1”直通第一个foo出现的数字是“4”。没有 中没有人,我可以无论是作为参考使用属性...

有没有办法使用XSL来实现这一目标?

我已经成功地循环遍历所有foo的事件(使用xsl:for-each属性),但棘手的部分是为每个foo循环包含以下foo2元素。

编辑: 让我们假装ATTR具有随机值,如:

<foo attr1="abc"/> 
<foo2 num="1"/> 
<foo2 num="2"/> 
<foo2 num="3"/> 
<foo2 num="4"/> 
<foo attr1="def"/> 
<foo2 num="1"/> 

我想要做的是组ABC及以下Foo的一个表中,因此:

+--------+-----+ 
| abc | def | 
| 1  | 1 | 
| 2  |  | 
| 3  |  | 
| 4  |  | 
+--------------+ 

无不幸的是它不支持xslt 2.0。

+0

** ** 1你的问题并不完全清楚。请告诉我们预期的输出。 ** 2。**您的处理器是否支持XSLT 2.0? –

+0

@ michael.hor257k我刚刚更新了我的帖子。 – Mnemonics

回答

1

您这里有两个单独的问题:

  1. 如何分组的节点,使用XSLT 2.0的group-starting-with的等效;

  2. 如何转(旋转)的结果,这样就可以建立每个组占用一个表格 - 即使一个HTML表的构造一行一行地

我建议你分两次做到这一点:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:exsl="http://exslt.org/common" 
extension-element-prefixes="exsl"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 

<xsl:key name="grp" match="foo2" use="generate-id(preceding-sibling::foo[1])" /> 

<!-- first-pass --> 
<xsl:variable name="groups-rtf"> 
    <xsl:for-each select="root/foo"> 
     <group name="{@attr1}"> 
      <xsl:for-each select="key('grp', generate-id())"> 
       <item><xsl:value-of select="@num"/></item> 
      </xsl:for-each> 
     </group> 
    </xsl:for-each> 
</xsl:variable> 
<xsl:variable name="groups" select="exsl:node-set($groups-rtf)/group" /> 

<xsl:template match="/"> 
    <table border="1"> 
     <!-- header row --> 
     <tr> 
      <xsl:for-each select="$groups"> 
       <th><xsl:value-of select="@name"/></th> 
      </xsl:for-each> 
     </tr>  
     <!-- data rows --> 
     <xsl:call-template name="generate-rows"/> 
    </table> 
</xsl:template> 

<xsl:template name="generate-rows"> 
    <xsl:param name="i" select="1"/> 
    <xsl:if test="$groups/item[$i]"> 
     <tr> 
      <xsl:for-each select="$groups"> 
       <td><xsl:value-of select="item[$i]"/></td> 
      </xsl:for-each> 
     </tr> 
     <xsl:call-template name="generate-rows"> 
      <xsl:with-param name="i" select="$i + 1"/> 
     </xsl:call-template> 
    </xsl:if> 
</xsl:template> 

</xsl:stylesheet> 

应用到下面的例子输入:

XML

<root> 
    <foo attr1="abc"/> 
    <foo2 num="1"/> 
    <foo2 num="2"/> 
    <foo2 num="3"/> 
    <foo2 num="4"/> 
    <foo attr1="def"/> 
    <foo2 num="5"/> 
    <foo2 num="6"/> 
</root> 

的(渲染)的结果将是:

enter image description here

相关问题