【问题标题】:XML Stylesheet XSL, multiple structure for same itemXML 样式表 XSL,同一项目的多个结构
【发布时间】:2014-04-17 16:42:47
【问题描述】:

这是我的 xml 部分:

<record>
   <BillNum>999</BillNum>
   <Item>Glasses</Item>
   <Price>100</Price>
</record>
<record>
   <BillNum>999</BillNum>
   <Item>Book</Item>
   <Price>50</Price>
</record>
<record>
   <BillNum>999</BillNum>
   <Item>Shoes</Item>
   <Price>500</Price>
</record>

现在,我想为这个 xml 编写 xsl,它可以设置如下样式:

<table>
        <tr>
            <td>Item</td>
            <td>Price</td>
        </tr>
        <tr>
            <td>Glasses</td>
            <td>100</td>
        </tr>
        <tr>
            <td>Book</td>
            <td>50</td>
        </tr>
        <tr>
            <td>Shoes</td>
            <td>500</td>
        </tr>
</table>

对于每个 BillNum。

请帮帮我,我怎样才能写出所需的xsl?

谢谢

【问题讨论】:

  • 您想使用 XSLT 2.0 还是 1.0?您是要为所有数据创建一个表,还是为每组具有相同BillNumrecords 创建一个表?
  • @MartinHonnen XSLT 1.0,我想为每组具有相同 BillNum 的记录创建一个表。

标签: html xml xslt


【解决方案1】:

这是一个分组问题,在 XSLT 1.0 中使用带有键的 Muenchian 分组 http://www.jenitennison.com/xslt/grouping/muenchian.xml 来解决

<xsl:key name="bill" match="record" use="BillNum"/>

<xsl:template match="NameOfParentOfRecordHere">
  <xsl:apply-templates select="record[generate-id() = generate-id(key('bill', BillNum)[1])]" mode="table"/>
</xsl:template>

<xsl:template match="record" mode="table">
<table>
        <tr>
            <td>Item</td>
            <td>Price</td>
        </tr>
        <xsl:apply-templates select="key('bill', BillNum)"/>
</table>
</xsl:template>

<xsl:template match="record">
  <tr>
    <xsl:apply-templates select="Item | Price"/>
  </tr>
</xsl:template>

<xsl:template match="Item | Price">
  <td><xsl:value-of select="."/></td>
</xsl:template>

然后用模板设置HTML文档结构

<xsl:template match="/">
  <html>
    <head>
      <title>Example</title>
    </head>
    <body>
      <xsl:apply-templates/>
    </body>
  </html>
</xsl:template>

【讨论】:

  • 这在 IE 中给出了正确的表格格式,但在 Firefox 中它以简单的文本格式显示:ItemPriceGlasses100Book50Shoes500
  • 嗯,我已经发布了需要合并到完整样式表中的 sn-ps,以确保浏览器知道您正在创建 HTML 输出,方法是在其中放置 &lt;xsl:output method="html"/&gt; 或通过模板创建html 根元素。我也会进行编辑以显示这一点。
  • 现在 firefox 显示正确的表格,但 Chrome 显示空白页 :(
  • 如何在 Chrome 中加载 XML?它对从文件系统加载的文件具有非常严格的安全设置,例如禁用&lt;?xml-stylesheet?&gt;。因此,对于 Chrome,请确保您通过 HTTP 加载 XML 文档或以较低的安全设置启动 Chrome,否则它将永远不会加载 XML 文档中引用的 XSLT。检查其错误控制台是否显示任何解释空白页的内容。
  • 在记录的模板中使用sum(key('bill', BillNum)/Price) 将计算组中所有项目的所有Price 元素的总和。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 2012-04-03
  • 2014-12-20
  • 2012-11-02
  • 2012-04-01
  • 1970-01-01
相关资源
最近更新 更多