Java XML输出 – 子项的正确缩进

我想将一些简单的数据模型序列化为xml,我一直在使用标准的java.org.w3c相关代码(见下文),缩进比没有“OutputKeys.INDENT”好,但还有一点点剩下的东西 – 适合儿童元素的缩进。

我知道之前已经在stackoverflow上询问过,但是这个配置对我来说不起作用,这是我正在使用的代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); doc = addItemsToDocument(doc); // The addItemsToDocument method adds childElements to the document. TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", new Integer(4)); // switching to setAttribute("indent-number", 4); doesn't help Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(outFile); // outFile is a regular File outFile = new File("some/path/foo.xml"); transformer.transform(source, result); 

产生的输出是:

       

而我想要它(为了更清晰),如:

       

我只是想知道是否有这样做的方法,使它适当缩进为子元素。

先感谢您 !
复活节快乐编码:-)!

如果您使用的Transformer实现是Xalan-J,那么您应该能够使用:

 transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "5"); 

另见: http : //xml.apache.org/xalan-j/usagepatterns.html

 import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4"); 
 Document doc; ..... TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(new DOMSource(doc), new StreamResult(new File("filename.xml"))); transformer.transform(new DOMSource(doc), new StreamResult(System.out));