tags:

views:

98

answers:

2

I'd like to merge 2 XML streams (strings) in Java, necessarily by XSLT (that I could change the transformation), but the problem is that the XMLs come as a string. There are many examples, but through the files. Can this be done without saving them in files?

Thanks.

A: 

Have a look at this tutorial, it has all you need (with examples).

If you want to transform XML that comes in in String format, use something like:

Templates template = ...;
String xml = ...;
Transformer transformer = template.newTransformer();
Writer out = new StringWriter();
transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(out));
mindas
This does answer how to get the input document from a String. But the question is about how to merge two documents. One of the documents must be read by the transform itself (as in the third example of the tutorial), or given as a parameter.
Christian Semrau
+1  A: 

I only know about a way using an own implementation of URIResolver.

public final class StringURIResolver implements URIResolver {
    Map<String, String> documents = new HashMap<String, String>();

    public StringURIResolver put(final String href, final String document) {
        documents.put(href, document);
        return this;
    }

    public Source resolve(final String href, final String base)
    throws TransformerException {
        final String s = documents.get(href);
        if (s != null) {
            return new StreamSource(new StringReader(s));
        }
        return null;
    }
}

Use it like this:

final String document1 = ...
final String document2 = ...
final Templates template = ...
final Transformer transformer = template.newTransformer();
transformer.setURIResolver(new StringURIResolver().put("document2", document2));
final StringWriter out = new StringWriter();
transformer.transform(new StreamSource(new StringReader(document1)),
    new StreamResult(out));

And in the transform, reference it like this:

<xsl:variable name="document2" select="document('document2')" />
Christian Semrau
Yes!!! It works!!! Thank you very much!!! :))