【问题标题】:How to transform XML with entries of key value pairs to a HTML table?如何将带有键值对条目的 XML 转换为 HTML 表?
【发布时间】:2012-03-07 20:09:52
【问题描述】:

我有多个具有键值对的实体(在我的示例中为<data>)。每个实体都包含相同顺序的相同键,但我不知道哪个和多少。如何使用 XSLT 将其转换为 HTML 表格,在表格标题中包含键,在表格行中包含实体的值?

<data>
  <entry>
     <key>id</key><value>12345</value>
  </entry>
  <entry>
     <key>price</key><value>12.45</value>
  </entry>
  <entry>
      <key>country</key><value>UK</value>
  </entry>
<data>
<data>
  <entry>
     <key>id</key><value>67890</value>
  </entry>
  <entry>
     <key>price</key><value>67.89</value>
  </entry>
  <entry>
      <key>country</key><value>DE</value>
  </entry>
<data>

...应该变成...

<tr><th>id</th><th>price</th><th>country</th></tr>
<tr><td>12345</td><td>12.45</td><td>UK</td></tr>
<tr><td>67890</td><td>67.89</td><td>DE</td></tr>

【问题讨论】:

    标签: html xml xslt xpath xhtml


    【解决方案1】:

    用途:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
        <xsl:output method="xml" indent="yes"/>
    
        <xsl:template match="/">
            <table>
                <tr>
                    <xsl:for-each select="//data[1]/entry">
                        <th>
                            <xsl:value-of select="key"/>
                        </th>
                    </xsl:for-each>
                </tr>
    
                <xsl:apply-templates select="//data"/>
            </table>
        </xsl:template>
    
        <xsl:template match="data">
            <tr>
                <xsl:apply-templates select="entry"/>
            </tr>
        </xsl:template>
    
        <xsl:template match="entry">
            <td>
                <xsl:value-of select="value"/>
            </td>
        </xsl:template>
    </xsl:stylesheet>
    

    输出:

    <table>
      <tr>
        <th>id</th>
        <th>price</th>
        <th>country</th>
      </tr>
      <tr>
        <td>12345</td>
        <td>12.45</td>
        <td>UK</td>
      </tr>
      <tr>
        <td>67890</td>
        <td>67.89</td>
        <td>DE</td>
      </tr>
    </table>
    

    【讨论】:

    • 如何将 xsl 应用到 xml 中?
    • @sinsedrix,你是什么意思?
    • 我尝试在 XML 标头中添加 &lt;?xml-stylesheet href="data.xsl" type="text/xsl"?&gt;,但它根本不生成 HTML :(
    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2023-03-08
    • 2019-01-23
    • 1970-01-01
    相关资源
    最近更新 更多