I'm trying to use server-side XSLT via Java for the first time. My attempt has been largely successful, except for one little quirk.

Here's how a certain field in the input file looks:
Code XML:

And this is the associated template in the XSL style sheet:
Code XML:
<xsl:param name="baseurl">http://example.com</xsl:param>
<xsl:template match="foo/text()">
  <a href="{$baseurl}{.}"><xsl:value-of select="."/></a>

I'm using javax.xml.parsers.DocumentBuilder to parse the input and the XSL style sheet. Then I use javax.xml.transform.TransformerFactory to create a transform. Finally, I want to serialise the result as a string, so I do,
ByteArrayOutputStream out = new ByteArrayOutputStream();
trans.transform(new DOMSource(src), new StreamResult(out));
result = out.toString("UTF-8");
It works nicely, except that special characters aren't properly escaped in attribute values. For the example above, the generated output would be,
<a href="http://example.com/path/file?x=1&y=2&z=3">http://example.com/path/file?x=1&amp;y=2&amp;z=3</a>
As you can see, the ampersands are escaped in the link text, but not in the href attribute value. I've tried using <xsl:element/> and <xsl:attribute/>, but the result is the same.

It looks to me as if it's the javax.xml.transform.stream.StreamResult class that doesn't serialise the transformed DOM tree correctly.

Any ideas on how to make it behave would be greatly appreciated. I would prefer not to have to write my own serialisation class just for this.