我試圖使用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。
這裏有什麼明顯的錯誤?
該屬性解決了我的問題!謝謝! +1 – 2013-05-21 16:00:31