要温柔。
我正在尝试使用 javax.xml.transform.Transformer 格式化一些 xml 字符串以在标签之间缩进/无空格。如果标签之间没有空格,则可以正常工作。如果有它的行为很奇怪。我会发布一个例子。我试图跟进以下主题: http://forums.sun.com/thread.jspa?messageID= 2054303#2699961。没有成功。
要遵循的代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation domImpl = builder.getDOMImplementation();
DOMImplementationLS ls = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
LSInput in = ls.createLSInput();
in.setByteStream(new ByteArrayInputStream(input.getBytes()));
LSParser parser = ls.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS,
"http://www.w3.org/2001/XMLSchema");
Document xmlInput = parser.parse(in);
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory f = TransformerFactory.newInstance();
f.setAttribute("indent-number", 2);
Transformer transformer = f.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(new DOMSource(xmlInput), xmlOutput);
如果标签之间没有中断
input : <tag><nested> hello </nested></tag>
output :
<tag>
<nested> hello </nested>
</tag>
如果有 :
input : <tag> <nested> hello </nested></tag>
output :
<tag> <nested> hello </nested>
</tag>
JVM 1.6。
这里有什么明显的错误吗?