我用来处理XSLT
和XML
文件的常规Java代码是:
public static final String transformXmlDocument(String inputXmlString,
File xsltFile) {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslt = new StreamSource(xsltFile);
StreamSource text = new StreamSource(new StringReader(inputXmlString));
StringWriter writer = new StringWriter();
StreamResult textOP = new StreamResult(writer);
try {
Transformer transformer = factory.newTransformer(xslt);
transformer.transform(text, textOP);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e2) {
e2.printStackTrace();
}
String results = writer.toString();
return results;
}
我必须处理XSLT
3.0版本才能使用以下功能:
解析的XML片段()
这个版本的XSLT
会抛出错误:
parse-xml-fragment()未找到函数
我的输入XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data>
<![CDATA[<pi>hi</pi>]]>
</data>
XSLT代码:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:data="http://example.com/data"
xmlns:text="http://exselt.net/text"
xmlns:err="http://www.w3.org/2005/xqt-errors"
exclude-result-prefixes="xs xsl data text err"
version="3.0">
<xsl:output indent="yes"/>
<xsl:template match="/">
<xsl:variable name="sample">
<xsl:copy-of select="parse-xml-fragment('<gi>surface</gi><gi>surface</gi><gi>surface</gi>')" />
</xsl:variable>
<final>
<xsl:copy-of select="data/pi"/>
<xsl:for-each select="$sample/gi">
<pi><xsl:value-of select="."/></pi>
</xsl:for-each>
</final>
</xsl:template>
</xsl:stylesheet>
预期产出:
<final>
<pi>hi</pi>
<pi>surface</pi>
<pi>surface</pi>
<pi>surface</pi>
</final>
有人可以提供解决方案吗?
答案 0 :(得分:2)
您需要确保Saxon 9.8 HE或PE或EE在您的课程路径上,HE位于Sourceforge和Maven,商业版PE和EE来自saxonica.com 。在安装特定版本后,请参阅http://saxonica.com/html/documentation/about/installationjava/installingjava.html和http://saxonica.com/html/documentation/using-xsl/embedding/jaxp-transformation.html,以便使用,例如http://saxonica.com/html/documentation/javadoc/net/sf/saxon/TransformerFactoryImpl.html直接而不是依赖于JAXP类加载器机制,所以假设你安装了Saxon 9.8 HE,你可以替换
TransformerFactory factory = TransformerFactory.newInstance();
带
TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();