这个问题的最高答案描述了一种在Java中实现高效XSLT管道的技术:
Efficient XSLT pipeline in Java (or redirecting Results to Sources)
变压器.java
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.Templates;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.Transformer;
import java.io.File;
public class MyTransformer {
public static void main(String[] args) throws javax.xml.transform.TransformerConfigurationException, javax.xml.transform.TransformerException{
SAXTransformerFactory stf = (SAXTransformerFactory)TransformerFactory.newInstance();
// These templates objects could be reused and obtained from elsewhere.
Templates templates1 = stf.newTemplates(new StreamSource( new File("MyStylesheet1.xslt")));
Templates templates2 = stf.newTemplates(new StreamSource(new File("MyStylesheet2.xslt")));
TransformerHandler th1 = stf.newTransformerHandler(templates1);
TransformerHandler th2 = stf.newTransformerHandler(templates2);
th1.setResult(new SAXResult(th2));
th2.setResult(new StreamResult(System.out));
Transformer t = stf.newTransformer();
//SETTING PARAMETERS HERE
t.setParameter("foo","this is from param 1");
t.setParameter("bar","this is from param 2");
t.transform(new StreamSource(new File("in.xml")), new SAXResult(th1));
// th1 feeds th2, which in turn feeds System.out.
}
}
<?xml version="1.0"?>
<stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:foo="urn:foo" version="1.0">
<output method="xml"/>
<param name="foo"/>
<template match="@*|node()">
<copy>
<apply-templates select="@*|node()"/>
</copy>
</template>
<template match="foo:my/foo:hello">
<copy>
<foo:world>
foo is : <value-of select="$foo"/>
</foo:world>
</copy>
</template>
</stylesheet>
MyStylesheet2.xslt
<?xml version="1.0"?>
<stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:foo="urn:foo" version="1.0">
<output method="xml"/>
<param name="bar"/>
<template match="@*|node()">
<copy>
<apply-templates select="@*|node()"/>
</copy>
</template>
<template match="foo:my/foo:hello/foo:world">
<copy>
<apply-templates select="@*|node()"/>
<attribute name="attr">
<value-of select="$bar"/>
</attribute>
</copy>
</template>
</stylesheet>
<my xmlns="urn:foo">
<hello/>
</my>
它提供了以下输出:
<?xml version="1.0" encoding="UTF-8"?><my xmlns="urn:foo">
<hello><foo:world xmlns:foo="urn:foo">foo is : </foo:world></hello>
</my>
如你所见foo:world/@属性为空,并且福:世界说“foo is:”。预期的行为是,应该用传递到setParameter方法中的参数填充它们。
有没有一种方法可以使用这种技术设置XSL转换参数。如果没有,有人能推荐一种替代技术来在Java中高效地转换样式表吗,比如可以设置XSLT参数?