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

Apache Camel+Spring Boot下如何用XSLT生成XML并遍历数组

嘿,我来帮你解决这个XSLT遍历的问题!

首先得明确一点:你用marshal(xStreamDataFormat)把JDBC返回的List<Map>序列成XML后,XStream生成的结构大概是这样的(默认配置下):

<list>
  <map>
    <entry>
      <string>name</string>
      <string>emp1</string>
    </entry>
    <entry>
      <string>id</string>
      <string>1</string>
    </entry>
  </map>
  <map>
    <entry>
      <string>name</string>
      <string>emp2</string>
    </entry>
    <entry>
      <string>id</string>
      <string>2</string>
    </entry>
  </map>
</list>

每个<map>对应一条员工记录,里面的<entry>存着字段名和值。接下来你的XSLT只需要遍历这些<map>节点,提取对应的值就行。

你的sample.xslt可以这么写

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- 匹配根节点<list> -->
    <xsl:template match="/list">
        <employees>
            <!-- 遍历每一个<map>节点,也就是每一条员工数据 -->
            <xsl:for-each select="map">
                <employee>
                    <!-- 提取name字段:找到key为name的entry,取第二个<string>的内容 -->
                    <name>
                        <xsl:value-of select="entry[string[1]='name']/string[2]"/>
                    </name>
                    <!-- 提取id字段:同理找到key为id的entry -->
                    <id>
                        <xsl:value-of select="entry[string[1]='id']/string[2]"/>
                    </id>
                </employee>
            </xsl:for-each>
        </employees>
    </xsl:template>
</xsl:stylesheet>

额外的小优化(可选)

如果你觉得XStream生成的默认XML结构不够直观,可以给List和Map设置别名,让XML更清晰:

// 在配置XStreamDataFormat的时候添加别名
XStreamDataFormat xStreamDataFormat = new XStreamDataFormat();
// 把List别名为employeesList,Map别名为employeeRecord
Map<String, Class<?>> aliases = new HashMap<>();
aliases.put("employeesList", List.class);
aliases.put("employeeRecord", Map.class);
xStreamDataFormat.setAliases(aliases);

这时候生成的XML根节点会是<employeesList>,每条记录是<employeeRecord>,对应的XSLT里的匹配节点也要改成/employeesList和employeeRecord就行。

现在你运行路由,应该就能得到你想要的<employees>结构的XML啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:02:44