使用xslt将xml列表转换为具有多列的html表格 [英] Use xslt to convert xml list into html table with multiple columns

查看:270
本文介绍了使用xslt将xml列表转换为具有多列的html表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <项目>假设我有一个xml文档,其中包含一个如下所示的列表: 
< Item> First Item< / Item>
< Item>第二项< / Item>
< Item>第三项< / Item>
< Item> 4< / Item>
< Item> Five< / Item>
< / Items>

我想将它转换为一个有两列的Item元素的html表格(我不是

 < pre $>< code><表> 
< tr>
< td>第一项< / td>
< td>第二项< / td>
< / tr>
< tr>
< td>第三项< / td>
< td> 4< / td>
< / tr>
< tr>
< td> Five< / td>
< td>< / td>
< / tr>
< / table>

据我所知,我可以通过以下xslt转换获得带有单列的表,但不能找出如何获得多列。

 < table> 
< xsl:for-each select =Items>
< tr>
< td>< xsl:value-of select =Item/>< / td>
< / tr>
< / xsl:for-each>
< / table>


解决方案

试试这个:

 < xsl:stylesheet version =1.0
xmlns:xsl =http://www.w3.org/1999/XSL/Transform >
< xsl:template match =/ Items>
< table>
< xsl:for-each select =Item [position()mod 2 = 1]>
< xsl:variable name =posselect =position() - 1/>
< tr>
< td>< xsl:value-of select =。/>< / td>
< td>< xsl:value-of select =// Item [position()=($ pos * 2)+ 2]/>< / td>
< / tr>
< / xsl:for-each>
< / table>
< / xsl:template>
< / xsl:stylesheet>


Say I have an xml document consisting of a list as shown below:

<Items>
  <Item>First Item</Item>
  <Item>Second Item</Item>
  <Item>Third Item</Item>
  <Item>4</Item>
  <Item>Five</Item>
</Items>

I want to convert it to a html table with two columns for the Item elements (I'm not fussed at the moment whether it's ordererd top-bottom-left-right or left-right-top-bottom).

<table>
  <tr>
    <td>First Item</td>
    <td>Second Item</td>
  </tr>
  <tr>
    <td>Third Item</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Five</td>
    <td></td>
  </tr>
</table>

I understand I can get a table with a single column with the following xslt transform, but can't figure out how to get multiple columns.

<table>
  <xsl:for-each select="Items">
    <tr>
      <td><xsl:value-of select="Item"/></td>
    </tr>
  </xsl:for-each>
</table>

解决方案

Try this:

<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/Items">
    <table>
      <xsl:for-each select="Item[position() mod 2 = 1]">
        <xsl:variable name="pos" select="position() - 1" />
        <tr>
          <td><xsl:value-of select="."/></td>
          <td><xsl:value-of select="//Item[position() = ($pos * 2) + 2]"/></td>
        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>
</xsl:stylesheet>

这篇关于使用xslt将xml列表转换为具有多列的html表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆