我要求在XSLT中从Java地图获取数据。 我知道使用xalan我可以实现它,但我们依赖于常见的Transformer,这迫使我们使用Saxon-HE。 我将java映射传递给变量并在XSLT中获取它。 请告知我们如何实现这一目标。
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*" />
<xsl:param name="sequenceNbrMap" />
</xsl>
我需要根据动态键从此地图中获取值,此地图也是动态的,因此我无法直接将此地图创建为XSLT。
答案 0 :(得分:1)
只能通过扩展功能访问Java地图,扩展功能在Saxon-HE中具有有限的可用性。有关Saxon扩展功能的完整信息,请访问
http://www.saxonica.com/documentation/index.html#!extensibility
答案 1 :(得分:1)
尝试使用自定义URIResolver并将地图值提供为xml片段。
class MapEntryResolver implements URIResolver
{
private Map<String,String> map = new HashMap<>();
private static final String PREFIX = "map://";
@Override
public Source resolve(String href, String base)
throws TransformerException
{
Source snippet = null;
String key = href.replace(PREFIX, "");
if(map.containsKey(key))
{
snippet = new StreamSource(new StringReader("<" + key + ">" + map.get(key) + "</" + key + ">"));
}
return snippet;
}
public void setMap(Map<String,String> map)
{
this.map = map;
}
}
您可以使用xslt中的文档功能访问地图值。
<xsl:variable name="mapValue" select="document('map://foo')" />
样品:
//First create the resolver
MapEntryResolver uriResolver = new MapEntryResolver();
//pass your map
uriResolver.setMap(yourMap);
//and attach it to the factory
TransformerFactory factory = new TransformerFactoryImpl();
factory.setURIResolver(uriResolver);
Transformer transformer = factory.newTransformer(new StreamSource(this.getClass().getResourceAsStream(pathToYourXsl));
//start transform and store result
ByteArrayOutputstream result = new ByteArrayOutputstream();
transformer.transform(new StreamSource(pathToYourInputXml), new StreamResult(result));
UriResolver按需创建地图数据中的xml片段,如下所示:
<key>value</key>
在xsl中使用document函数通过提供map键作为参数来获取片段:
<!-- variable contains snippet <foo>bar</foo> -->
<xsl:variable name="mapValue" select="document('map://foo')" />
<!-- use it like any other doc-->
<xsl:value-of select="$mapValue/foo"/>