如何在XSLT中遍历Java字符串列表?
在XSLT中遍历Java字符串列表的可行方案
标准XSLT的xsl:for-each仅支持XML节点集,但在Java集成环境下,借助支持扩展的XSLT处理器,完全可以直接遍历Java字符串列表,以下是几种实用方法:
方法1:基于Apache Xalan的Java扩展遍历
Xalan支持直接调用Java API,通过迭代器递归遍历列表:
- 先声明扩展命名空间:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://xml.apache.org/xalan/java" exclude-result-prefixes="java">
- 遍历逻辑示例(假设传入的列表参数名为
javaStringList):
<xsl:template match="/"> <xsl:variable name="listIterator" select="java:iterator($javaStringList)"/> <xsl:call-template name="loopThroughList"> <xsl:with-param name="iterator" select="$listIterator"/> </xsl:call-template> </xsl:template> <xsl:template name="loopThroughList"> <xsl:param name="iterator"/> <!-- 判断是否还有下一个元素 --> <xsl:if test="java:hasNext($iterator)"> <xsl:variable name="currentStr" select="java:next($iterator)"/> <!-- 这里处理当前字符串,比如输出 --> <string-item><xsl:value-of select="$currentStr"/></string-item> <!-- 递归调用继续遍历 --> <xsl:call-template name="loopThroughList"> <xsl:with-param name="iterator" select="$iterator"/> </xsl:call-template> </xsl:if> </xsl:template>
方法2:先将Java列表转为XML节点集
如果不想依赖处理器扩展,可以在Java代码层把字符串列表转换成XML结构,再传入XSLT用标准xsl:for-each遍历:
Java侧伪代码:
List<String> strList = Arrays.asList("foo", "bar", "baz"); // 构建XML节点 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = doc.createElement("string-list"); for(String s : strList) { Element item = doc.createElement("item"); item.setTextContent(s); root.appendChild(item); } // 将root节点作为参数传入XSLT处理器
XSLT侧遍历:
<xsl:for-each select="$xmlStrList/item"> <output-item><xsl:value-of select="."/></output-item> </xsl:for-each>
方法3:使用Saxon(XSLT 2.0+)的原生Java集合支持
Saxon对Java集合的支持更简洁,直接在xsl:for-each中访问集合元素:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://saxon.sf.net/java-type" exclude-result-prefixes="java"> <xsl:param name="javaStringList" as="java:java.util.List"/> <xsl:template match="/"> <xsl:for-each select="$javaStringList?*"> <list-item><xsl:value-of select="."/></list-item> </xsl:for-each> </xsl:template> </xsl:stylesheet>
这里的?*是Saxon专属语法,用于遍历Java集合的元素。
内容的提问来源于stack exchange,提问作者JohnyRocket85
相关产品推荐
相关产品推荐

