我正在使用 Java 的内置 XML 转换器来获取 DOM 文档并打印出生成的 XML。问题在于,尽管明确设置了参数“缩进”,但它根本没有缩进文本。
示例代码
public class TestXML {
public static void main(String args[]) throws Exception {
ByteArrayOutputStream s;
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Transformer t = TransformerFactory.newInstance().newTransformer();
Element a,b;
a = d.createElement("a");
b = d.createElement("b");
a.appendChild(b);
d.appendChild(a);
t.setParameter(OutputKeys.INDENT, "yes");
s = new ByteArrayOutputStream();
t.transform(new DOMSource(d),new StreamResult(s));
System.out.println(new String(s.toByteArray()));
}
}
结果
<?xml version="1.0" encoding="UTF-8" standalone="no"?><a><b/></a>
想要的结果
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>
<b/>
</a>
想法?
最佳答案
您需要启用 'INDENT' 并为转换器设置缩进量:
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
更新:
引用:How to strip whitespace-only text nodes from a DOM before serialization?
(非常感谢所有成员,尤其是 @marc-novakowski、@james-murty 和 @saad):
关于Java:如何缩进 Transformer 生成的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1384802/