Procesamiento XSLT con Java: pasar contenido xml en el parámetro

I would like to pass a parameter containing XML content when processing XSLT. Aquí está mi código:

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; 

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'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

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...

¿Cómo puedo hacer eso? Gracias.

preguntado el 02 de febrero de 12 a las 10:02

Why dont you strip the tags before passing the parameter?? -

You need to produce a analizado XML document and then pass this as the value of the parameter -- not the cadena you are now passing. Read your XSLT processor documentation how passing of parameters of type XMLDocument is supported. -

@Marc Maybe you should update your question to reflect how you want to process this parameter - since you dont want to just display it... -

@quaylar: ok done sorry my first post was confused. -

2 Respuestas

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>")));

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

Respondido 02 Feb 12, 17:02

You might want to check the documentation of your XSLT processor what kind of parameter types it allows and whether and how it allows to pass in a node and not a string. If I understand y,%20java.lang.Object) correctly then Saxon allows you to pass in nodes in the form of its NodeInfo.

Respondido 21 Oct 16, 14:10

Ok thanks will have a look at it because I'd like to pass xml so that I'll be able to select nodes in the XSL. - Marc

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.