Java XML输出 - 子项的正确缩进 [英] Java XML Output - proper indenting for child items

查看:152
本文介绍了Java XML输出 - 子项的正确缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to serialize some simple data model into xml, I've been using the standard java.org.w3c -related code (see below), the indentation is better than no "OutputKeys.INDENT", yet there is one little thing that remains - proper indentation for child elements.

我知道在 on stackoverflow ,但该配置对我不起作用,这是我正在使用的代码:

I know that this has been asked before on stackoverflow , yet that configuration did not work for me, this is the code I'm using :

        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>

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

Whereas I would want it (for more clarity) like :

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

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

I was just wondering if there is a way of doing this, make it properly indented for the child elements.

提前谢谢!

复活节快乐编码:-)!

Thank you in advance !
Happy Easter coding :-) !

推荐答案

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

If the Transformer implementation you're using is Xalan-J, then you should be able to use:

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

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

这篇关于Java XML输出 - 子项的正确缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆