将org.w3c.dom.Document
打印到stdout的最简单方法是什么?(a.k.a。格式化)?
答案 0 :(得分:173)
调用printDocument(doc, System.out)
,该方法如下所示:
public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
(indent-amount
是可选的,可能不适用于您的特定配置)
答案 1 :(得分:13)
怎么样:
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(doc);
答案 2 :(得分:10)
使用一个班轮试试jcabi-xml:
String xml = new XMLDocument(document).toString();
这是您需要的依赖项:
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-xml</artifactId>
<version>0.14</version>
</dependency>
答案 3 :(得分:3)
private void printNode(Node rootNode, String spacer) {
System.out.println(spacer + rootNode.getNodeName() + " -> " + rootNode.getNodeValue());
NodeList nl = rootNode.getChildNodes();
for (int i = 0; i < nl.getLength(); i++)
printNode(nl.item(i), spacer + " ");
}
答案 4 :(得分:1)
这将使用递归下降/上升返回格式良好的输出。
private static boolean skipNL;
private static String printXML(Node rootNode) {
String tab = "";
skipNL = false;
return(printXML(rootNode, tab));
}
private static String printXML(Node rootNode, String tab) {
String print = "";
if(rootNode.getNodeType()==Node.ELEMENT_NODE) {
print += "\n"+tab+"<"+rootNode.getNodeName()+">";
}
NodeList nl = rootNode.getChildNodes();
if(nl.getLength()>0) {
for (int i = 0; i < nl.getLength(); i++) {
print += printXML(nl.item(i), tab+" "); // \t
}
} else {
if(rootNode.getNodeValue()!=null) {
print = rootNode.getNodeValue();
}
skipNL = true;
}
if(rootNode.getNodeType()==Node.ELEMENT_NODE) {
if(!skipNL) {
print += "\n"+tab;
}
skipNL = false;
print += "</"+rootNode.getNodeName()+">";
}
return(print);
}
答案 5 :(得分:-1)
如果你使用dom4j,它将是dom4JDOM.asString()