如何从Java应用程序使用XSLT 3.0?

时间:2017-06-28 08:04:26

标签: java xml xslt xslt-2.0 xslt-3.0

我用来处理XSLTXML文件的常规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('&lt;gi&gt;surface&lt;/gi&gt;&lt;gi&gt;surface&lt;/gi&gt;&lt;gi&gt;surface&lt;/gi&gt;')" />
         </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>

有人可以提供解决方案吗?

1 个答案:

答案 0 :(得分:2)

您需要确保Saxon 9.8 HE或PE或EE在您的课程路径上,HE位于SourceforgeMaven,商业版PE和EE来自saxonica.com 。在安装特定版本后,请参阅http://saxonica.com/html/documentation/about/installationjava/installingjava.htmlhttp://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();