使用Java进行XSLT处理:在参数中传递xml内容 [英] XSLT Processing with Java : passing xml content in parameter

查看:146
本文介绍了使用Java进行XSLT处理:在参数中传递xml内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在处理 XSLT 时传递包含 XML 内容的参数。
这是我的代码:

I would like to pass a parameter containing XML content when processing XSLT. Here is my code:

import javax.xml.transform.Result; 
import javax.xml.transform.Source; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerException; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.stream.StreamResult; 
import javax.xml.transform.stream.StreamSource; 

File xmlFile = new File(xmlFilePath);
File xsltFile = new File(xslFilePath);
Source xmlSource = new StreamSource(xmlFile);
Result result = new StreamResult(System.out);

TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
trans.setParameter("foo", "<bar>Hello1</bar><bar>Hello2</bar>");
trans.transform(xmlSource, result);

然后我想在我的XSL文件中选择'bar'标签中包含的值。

Then I'd like to select the values contained in the 'bar' tag in my XSL file.

<xsl:param name="foo"/>
...
<xsl:value-of select="$foo//foo[1]" />

但这不起作用,我收到此错误消息:

But this doesn't work, I get this error message:

org.apache.xpath.objects.XString cannot be cast to org.apache.xpath.objects.XNodeSet

所以我想我应该将XML对象传递给我的setParameter方法,但是哪一个?
我找不到一个如何创建XNodeSet对象的简单示例...

So I guess I should pass an XML object to my setParameter method, but which one? I can't find a simple example how to create an XNodeSet object...

我该怎么做?
谢谢。

How can I do that? Thanks.

推荐答案

如果您使用的是Saxon,最简单的解决方案是将StreamSource作为参数值传递:

If you are using Saxon, the simplest solution is to pass a StreamSource as the parameter value:

setParameter("foo", new StreamSource(new StringReader("<bar>baz</bar>")));

但这可能不适用于其他处理器:JAXP让它实现定义了什么类型的Object可以作为参数值传递。

But this might not work with other processors: JAXP leaves it implementation-defined what kinds of Object can be passed as parameter values.

这篇关于使用Java进行XSLT处理:在参数中传递xml内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆