Using Transformer in java for multiple outputs from an XSLT?

廉价感情. 提交于 2019-12-13 20:28:35

问题


I'm currently trying to get my code to call in an xml file and an xsl - then perform the transformation and output multiple outcome files depending on the xml content.

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class TestTransformation {

public static void main(String[] args) throws TransformerException {

System.setProperty("javax.xml.transform.TransformerFactory","net.sf.saxon.TransformerFactoryImpl");
    TransformerFactory tFactory = TransformerFactory.newInstance();

    Source xslt = new StreamSource(new File("transformer.xslt"));

    Transformer transformer = tFactory.newTransformer(xslt);

    Source xmlText = new StreamSource(new File("data.xml"));

    transformer.transform(xmlText, new StreamResult(new File("output.xml")));

But i want the transform to produce multiple output files.. Any ideas would be greatly appreciated!!


回答1:


i want the transform to produce multiple output files.

You do that in the XSLT stylesheet itself: http://www.w3.org/TR/xslt20/#result-trees

This is assuming you are indeed using an XSLT 2.0 processor. In XSLT 1.0, you can use an EXSLT extension: http://exslt.org/exsl/elements/document/index.html instead - provided your processor supports it.




回答2:


You should use <xsl:result-document/> to produce multiple files (note that it's only available in version 2.0 of XSL). You also don't need to specify output file.

The following code shows how to deal with multiple output files:

public class TestTransformation {

    public static void main(String[] args) throws TransformerException {
        TransformerFactory tFactory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", TestTransformation.class.getClassLoader());
        Source xslt = new StreamSource(new File("transformer.xslt"));
        Transformer transformer = tFactory.newTransformer(xslt);
        Source xmlText = new StreamSource(new File("data.xml"));
        transformer.transform(xmlText, new DOMResult());
    }
}

data.xml:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="hello.xsl"?>
<p>
    <p1>Hello world!</p1>
    <p2>Hello world!</p2>
</p>

transformer.xml:

<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="p1">
        <xsl:result-document href="foo.xml"/>
    </xsl:template>
    <xsl:template match="p2">
        <xsl:result-document href="bar.xml"/>
    </xsl:template>
</xsl:stylesheet>


来源:https://stackoverflow.com/questions/30562483/using-transformer-in-java-for-multiple-outputs-from-an-xslt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!