XSLT processing with Java: passing xml content in parameter

I want 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); 

Then I would 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 does not work, I get this error message:

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

So, I assume that I should pass the XML object to my setParameter method, but which one? I cannot find a simple example of creating an XNodeSet ...

How can i do this? Thanks.

+1
java xml xslt
source share
2 answers

If you use Saxon, the easiest solution is to pass the StreamSource as a parameter value:

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

But this may not work with other processors: JAXP leaves it with an implementation, which objects can be passed as parameter values.

+6
source share

You might want to check the documentation of your XSLT processor, what types of parameters it allows, and how and how it can pass a node, not a string. If I understand correctly http://www.saxonica.com/html/documentation/using-xsl/embedding/jaxp-transformation.html and http://www.saxonica.com/html/documentation/javadoc/net/sf/ saxon / jaxp / TransformerImpl.html # setParameter (java.lang.String,% 20java.lang.Object) , then Saxon allows you to pass in nodes as its NodeInfo .

+2
source share

All Articles