出于某种原因,我的下面的代码提供了例外: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;
}
它出了什么问题?
答案 0 :(得分:5)
我认为问题在于,当您将字符串作为参数传递给StreamSource时,它希望它是XML文档的URL,而不是实际的XML字符串本身。
您可能需要在此处使用StringReader阅读器:
String source = "...XSL Here...";
StringReader xsltReader = new StringReader(source);
Source xslt = new StreamSource(xsltReader);
Transformer transformer = factory.newTransformer(xslt);
您可能必须对XML执行相同的操作,假设您传入的是XML,而不是XML文档的URL。
StringReader xmlReader = new StringReader(xml);
Source text = new StreamSource(xmlReader);
对于转换本身,您可能需要使用StringWriter
StringWriter writer = new StringWriter();
transformer.transform(text, new StreamResult(writer));
result = writer.toString();
答案 1 :(得分:0)
问题是因为编码..当你使用File()类读取文件时,它在内部进行编码..但是当你尝试将XML加载为字符串..那么你必须手动完成..
观察.getBytes() and ByteArrayInputStream(bytes).
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>";
byte[] bytes = source .getBytes("UTF-16");
Source xslsource = new StreamSource(new ByteArrayInputStream(bytes));
Transformer transformer = factory.newTransformer(xslsource);
替代解决方案是使用StringReader:
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>";
StringReader xslReader = new StringReader(source);
Source xslsource= new StreamSource(xslReader);
自动处理编码..