You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

需求:编写XSLT样式表匹配XML元素并生成HTML表格

解决XSLT匹配 ID与第三个值的问题

第一步:明确XML结构示例

假设你的XML结构如下(符合需求场景):

<root>
  <items>
    <item>101</item>
    <item>102</item>
    <item>103</item> <!-- 目标匹配的ID值 -->
    <VIP>Yes</VIP>
  </items>
  <objects>
    <object ID="101" name="Object A"/>
    <object ID="103" name="Object C"/> <!-- 符合匹配条件的元素 -->
    <object ID="102" name="Object B"/>
  </objects>
</root>

第二步:编写XSLT样式表

下面的样式表可实现需求,核心是通过变量存储目标ID和VIP值,再精准筛选匹配的<object>:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>

  <!-- 存储第三个<item>的ID值 -->
  <xsl:variable name="target-id" select="/root/items/item[3]/text()"/>
  <!-- 存储对应的VIP状态 -->
  <xsl:variable name="vip-status" select="/root/items/VIP/text()"/>

  <xsl:template match="/">
    <html>
      <body>
        <table border="1">
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>VIP</th>
          </tr>
          <!-- 筛选ID属性等于目标ID的<object>元素 -->
          <xsl:for-each select="/root/objects/object[@ID = $target-id]">
            <tr>
              <td><xsl:value-of select="@ID"/></td>
              <td><xsl:value-of select="@name"/></td>
              <td><xsl:value-of select="$vip-status"/></td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

关键要点说明

  1. 变量复用:将第三个<item>的值和<VIP>值存入变量,既避免重复编写路径,也确保上下文引用的准确性。
  2. 匹配逻辑:通过@ID = $target-id直接筛选符合条件的<object>,注意根据实际XML结构调整<object>的XPath路径(比如如果<object>不在/root/objects下,需修改对应路径)。
  3. 上下文问题:确保<items>和<object>的根路径正确,避免因当前上下文变化导致无法定位目标节点。

最终输出的HTML表格

运行上述XSLT后,会生成如下表格:

<html>
  <body>
    <table border="1">
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>VIP</th>
      </tr>
      <tr>
        <td>103</td>
        <td>Object C</td>
        <td>Yes</td>
      </tr>
    </table>
  </body>
</html>

内容的提问来源于stack exchange,提问作者Mulder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:02:10