使用 XSLT 的 XML 到 HTML 表 [英] XML to HTML table with XSLT

查看:16
本文介绍了使用 XSLT 的 XML 到 HTML 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够将平面 xml 数据集转换为 html 表,但我无法找到适合我需要的语法示例.我想使用一个样式表,它可以将外观相似的数据集转换为带有可变列的 html 表.这意味着它不能使用除rows"和row"之外的任何硬编码元素名称.

I need to be able to turn a flat xml data sets into html tables, and I'm having trouble finding syntax examples that will fit my need. I would like to use one stylesheet that can convert similar looking data sets into html tables with variable columns. This means it can't use any hard coded element names besides "rows" and "row".

我想要的样式表可以转换:

The stylesheet I'm after would be able to convert:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <AccountId>BlPUAA0</AccountId>
    <AccountName>Initech</AccountName>
    <AcocuntStatus>Client</AcocuntStatus>
  </row>
  <row>
    <AccountId>CJxIAAW</AccountId>
    <AccountName>Intertrode</AccountName>
    <AcocuntStatus>Prospect</AcocuntStatus>
  </row>
</rows>

进入:

<table>
  <tr>
    <th>AccountId</th>
    <th>AccountName</th>
    <th>AcocuntStatus</th>
  </tr>
  <tr>
    <td>BlPUAA0</td>
    <td>Initech</td>
    <td>Client</td>
  </tr>
  <tr>
    <td>CJxIAAW</td>
    <td>Intertrode</td>
    <td>Client</td>
  </tr>
</table>

还有这个:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <AccountId>BlPUAA0</AccountId>
    <AccountName>Initech</AccountName>
  </row>
  <row>
    <AccountId>CJxIAAW</AccountId>
    <AccountName>Intertrode</AccountName>
  </row>
</rows>

进入这个:

<table>
  <tr>
    <th>AccountId</th>
    <th>AccountName</th>
  </tr>
  <tr>
    <td>BlPUAA0</td>
    <td>Initech</td>
  </tr>
  <tr>
    <td>CJxIAAW</td>
    <td>Intertrode</td>
  </tr>
</table>

推荐答案

我在发布问题后不久就有尝试解决这个问题的冲动,这就是我想到的.我猜这会让你等待 24 小时才能自己回答.

I had the urge to try to solve this shortly after posting the question, and here is what I came up with. I guess it makes you wait 24 hours before you can answer it yourself.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:template match="/">
    <table>
      <tr>
        <xsl:for-each select="rows/row[1]/*">
          <th>
            <xsl:value-of select ="local-name()"/>
          </th>
        </xsl:for-each>
      </tr>
      <xsl:for-each select="rows/row">
        <tr>
          <xsl:for-each select="*">
            <td>
              <xsl:value-of select="."/>
            </td>
          </xsl:for-each>
        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>
</xsl:stylesheet>

这篇关于使用 XSLT 的 XML 到 HTML 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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