【问题标题】:XSLT wrap elements with same attribute value (table with row attr)XSLT 包装具有相同属性值的元素(具有行属性的表)
【发布时间】:2017-02-14 16:17:20
【问题描述】:

我正在尝试将 XML 表从较大的项目转换为 HTML 表,而且我对这个 XSLT 游戏还很陌生。我找到了很多材料,但我还没有看到任何类似这个问题的东西,所以我想我会问:

<table name="my table (2 columns)">
  <!-- some column headers -->
  <colhddef colnum="1">This is column 1</colhddef>
  <colhddef colnum="2">This is column 2</colhddef>
  <entry row="1" colnum="1">entry 1</entry>
  <entry row="1" colnum="2">entry 2</entry>
  <entry row="2" colnum="1">entry 3</entry>
  <entry row="2" colnum="2">entry 4</entry>
  <entry row="3" colnum="1">entry 5</entry>
  <entry row="3" colnum="2">entry 6</entry>
  <entry row="4" colnum="1">entry 7</entry>
  <entry row="4" colnum="2">entry 8</entry>
</table>

我希望用&lt;tr&gt;&lt;/tr&gt; 将每组具有公共行属性的条目包装起来,并且确保将列适当地放置在表中不会有什么坏处。这可能比我做的要简单得多......但非常感谢任何帮助!

加分:我在哪里可以找到优质的 XSLT 学习资源?推荐书籍?等等?

再次提前致谢!

【问题讨论】:

标签: xml xslt


【解决方案1】:

这可能会让你开始:

<xsl:template match="table">
 <table>
  <xsl:apply-templates select="entry[@colnum='1']"/>
 </table>
</xsl:template>

<xsl:template match="entry[@colnum='1']">
 <xsl:param name='row'><xsl:value-of select='@row'/></xsl:param>
 <tr>
  <td><xsl:value-of select="."/></td>
  <xsl:apply-templates select="../entry[@row=$row][@colnum!=1]"/>
 </tr>
</xsl:template>

<xsl:template match="entry[@colnum!='1']">
 <td><xsl:value-of select="."/></td>
</xsl:template>

第一个模板创建一个&lt;table&gt;&lt;/table&gt;,并仅从table 节点中选择&lt;entry colnum='1'/&gt; 节点来填充它。

第二个模板将参数$row 设置为&lt;entry colnum='1'/&gt; 节点的row 属性值。然后它创建一个&lt;tr&gt;&lt;/tr&gt; 容器,并添加一个包含此条目文本的&lt;td&gt;&lt;/td&gt; 节点。最后,从父表中选择row属性匹配$row参数且colnum属性不为1的entry节点。

最后一个模板将这些选定的&lt;entry&gt; 节点(colnum 属性不为 1)转换为 &lt;td&gt;&lt;/td&gt; 节点。

输出:

<table>
  <tr>
    <td>entry 1</td>
    <td>entry 2</td>
  </tr>
  <tr>
    <td>entry 3</td>
    <td>entry 4</td>
  </tr>
  <tr>
    <td>entry 5</td>
    <td>entry 6</td>
  </tr>
  <tr>
    <td>entry 7</td>
    <td>entry 8</td>
  </tr>
</table>

【讨论】:

  • 谢谢!我看到我需要更好地使用这个项目的函数式编程风格。我需要解析的 XML 文件非常大,XSLT 很容易失控和杂乱无章。这比我的 for-each 尝试要干净得多。
猜你喜欢
  • 2015-01-08
  • 2020-04-04
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 2020-05-03
  • 2020-12-05
  • 1970-01-01
  • 2018-01-21
相关资源
最近更新 更多