For some reason my below code gives the exception: javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet
public String removePrettyPrint(String xml) throws TransformerException, TransformerFactoryConfigurationError {
String result = "";
TransformerFactory factory = TransformerFactory.newInstance();
String source = "<?xml version=\"1.0\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"> <xsl:output indent=\"no\" /> <xsl:template match=\"@*|node()\"> <xsl:copy> <xsl:apply-templates select=\"@*|node()\"/> </xsl:copy> </xsl:template></xsl:stylesheet>";
Source xslt = new StreamSource(source);
Transformer transformer = factory.newTransformer(xslt);
Source text = new StreamSource(xml);
transformer.transform(text, new StreamResult(result));
return result;
}
What is wrong with it?
I think the problem is that when you pass a string as a parameter to the StreamSource, it expects it to be a URL of an XML document, not the actual XML string itself.
You probably need to use a StringReader reader here:
You’ll probably have to do the same for the XML, assuming you are passing in XML, and not the URL to an XML document.
And for the transform itself, you may need to make use of a StringWriter