jdk输出带缩进格式xml的方法

jdk自己带有xml处理的功能,好像是用的xerces和xalan。输出xml文件时遇到一个没有缩进的问题,后来好不容易搜出解决办法,现记录如下,以便别人容易搜到。关键是这两句:

//t是Transformer
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");


顺便把从创建到输出的代码贴上,以便以后查看
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.newDocument();
doc.setXmlStandalone(true);
Element root = doc.createElement("root");
root.setAttribute("xmlns:sling", "http://sling.apache.org/jcr/sling/1.0");

Element content = doc.createElement("content");
content.setAttribute("type", "text");

root.appendChild(content);

doc.appendChild(root);

DOMSource src = new DOMSource(doc);
StreamResult sr = new StreamResult(System.out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.transform(src, sr);


输出的结果是:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:sling="http://sling.apache.org/jcr/sling/1.0">
  <content type="text"/>
</root>

你可能感兴趣的:(java,xml)