打印org.w3c.dom.Document到stdout的最简单方法是什么?
org.w3c.dom.Document
打印(又名格式化)到stdout最简单的方法是什么?
调用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
是可选的,可能不适用于您的特定configuration)
怎么样:
OutputFormat format = new OutputFormat(doc); format.setIndenting(true); XMLSerializer serializer = new XMLSerializer(System.out, format); serializer.serialize(doc);
用一个class轮尝试jcabi-xml :
String xml = new XMLDocument(document).toString();
这是你需要的依赖:
<dependency> <groupId>com.jcabi</groupId> <artifactId>jcabi-xml</artifactId> <version>0.14</version> </dependency>
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 + " "); }
这将通过使用recursion下降/上升返回一个很好的格式输出。
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); }
如果你使用dom4j,那将是dom4JDOM.asString()