【问题标题】:Java XML Output - proper indenting for child itemsJava XML 输出 - 子项的正确缩进
【发布时间】:2011-02-04 00:55:24
【问题描述】:

我想将一些简单的数据模型序列化为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>

我只是想知道是否有办法做到这一点,使其为子元素正确缩进。

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

【问题讨论】:

标签: java xml indentation


【解决方案1】:

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

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

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

【讨论】:

【解决方案2】:
import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory

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

【讨论】:

  • 不应在代码中的 com.sun.* 包上中继。更多信息请参考链接。link
【解决方案3】:
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));

【讨论】:

  • Op 表示这对他不起作用...检查问题中的链接。
  • 在我的情况下,它工作正常......似乎这个问题后来在库中修复了 bugs.openjdk.java.net/browse/JDK-5064280 修复了这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多