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

时间:2010-04-03 16:32:25

标签: java xml indentation

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

我知道在on 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);

产生的输出是:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stuffcontainer>
<stuff description="something" duration="240" title="abc">
<otherstuff />
</stuff>
</stuffcontainer>

而我希望它(为了更清晰),如:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stuffcontainer>
  <stuff description="something" duration="240" title="abc">
    <otherstuff />
  </stuff>
</stuffcontainer>

我只是想知道是否有这样做的方法,使其正确缩进为子元素。

提前谢谢!
复活节快乐编码:-)!

3 个答案:

答案 0 :(得分:15)

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

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

另请参阅:http://xml.apache.org/xalan-j/usagepatterns.html

答案 1 :(得分:2)

import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory

transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");

答案 2 :(得分:1)

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));