Dr1*_*1Ku 2 java xml indentation
我想将一些简单的数据模型序列化为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);
Run Code Online (Sandbox Code Playgroud)
产生的输出是:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stuffcontainer>
<stuff description="something" duration="240" title="abc">
<otherstuff />
</stuff>
</stuffcontainer>
Run Code Online (Sandbox Code Playgroud)
而我想要它(为了更清晰),如:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stuffcontainer>
<stuff description="something" duration="240" title="abc">
<otherstuff />
</stuff>
</stuffcontainer>
Run Code Online (Sandbox Code Playgroud)
我只是想知道是否有这样做的方法,使它适当缩进为子元素.
先感谢您 !
复活节快乐编码:-)!
Chr*_*her 15
如果您使用的Transformer实现是Xalan-J,那么您应该能够使用:
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "5");
Run Code Online (Sandbox Code Playgroud)
另见:http://xml.apache.org/xalan-j/usagepatterns.html
| 归档时间: |
|
| 查看次数: |
15116 次 |
| 最近记录: |