java xslt xml jar,Java中的Saxon:XSLT用于CSV到XML

And it converts a CSV file to an XML document. It does this when used with the following command on the command line:

java -jar saxon9he.jar -xsl:csv-to-xml.csv -it:main -o:output.xml

So now the question becomes: How do I do I do this in my Java code?

Right now I have code that looks like this:

TransformerFactory transformerFactory = TransformerFactory.newInstance();

StreamSource xsltSource = new StreamSource(new File("location/of/csv-to-xml.xsl"));

Transformer transformer = transformerFactory.newTransformer(xsltSource);

StringWriter stringWriter = new StringWriter();

transformer.transform(documentSource, new StreamResult(stringWriter));

String transformedDocument = stringWriter.toString().trim();

(The Transformer is an instance of net.sf.saxon.Controller.)

The trick on the command line is to specify "-it:main" to point right at the named template in the XSLT. This means you don't have to provide the source file with the "-s" flag.

The problem starts again on the Java side. Where/how would I specify this "-it:main"? Wouldn't doing so break other XSLT's that don't need that specified? Would I have to name every template in every XSLT file "main?" Given the method signature of Transformer.transform(), I have to specify the source file, so doesn't that defeat all the progress I've made in figuring this thing out?

Edit: I found the s9api hidden inside the saxon9he.jar, if anyone is looking for it.

解决方案

You are using the JAXP API, which was designed for XSLT 1.0. If you want to make use of XSLT 2.0 features, like the ability to start a transformation at a named template, I would recommend using the s9api interface instead, which is much better designed for this purpose.

However, if you've got a lot of existing JAXP code and you don't want to rewrite it, you can usually achieve what you want by downcasting the JAXP objects to the underlying Saxon implementation classes. For example, you can cast the JAXP Transformer as net.sf.saxon.Controller, and that gives you access to controller.setInitialTemplate(); when it comes to calling the transform() method, just supply null as the Source parameter.

Incidentally, if you're writing code that requires a 2.0 processor then I wouldn't use TransformerFactory.newInstance(), which will give you any old XSLT processor that it finds on the classpath. Use new net.sf.saxon.TransformerFactoryImpl() instead, which (a) is more robust, and (b) much much faster.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值