Saturday, July 12, 2008

Constructing StreamSource and StreamResult for JAXP transformation

Recently, I had some tough time converting file paths having spaces into correct StreamSource and StreamResult objects, to be used by the JAXP transformer.

I figured out that below suggestion is probably the best way to solve this issue.

String sourceSystemId = "file:///C:/... .xml"; (use like this, if you are sure that URI string doesn't contain any illegal characters, like spaces etc.)

OR

String sourceSystemId = (new File(pathname)).toURI().toString(); (this will correctly escape characters that are illegal in URIs)

Then, construct StreamSource or StreamResult like following

StreamSource source = new StreamSource(sourceSystemId);

StreamResult result = new StreamResult(outputSystemId);

A useful function exists in XPath 2.0, which applies the %HH escaping convention to a URI, escaping both disallowed characters and reserved characters such as "/" and ":" (encode-for-uri(string $uri-part) → string).

No comments: