Java如何将JDOM文档转换为字符串?
本示例演示如何使用方法将JDOMDocument对象转换为。StringXMLOutputter.outputString(Documentdoc)
package org.nhooo.example.jdom; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class JDOMDocumentToString { public static void main(String[] args) { Document document = new Document(); Element root = new Element("rows"); //为根元素创建一个子级。在这里我们可以看到如何 //设置xml元素的文本。 Element child = new Element("row"); child.addContent(new Element("firstname").setText("Alice")); child.addContent(new Element("lastname").setText("Mallory")); child.addContent(new Element("address").setText("Sunset Road")); //将子项添加到根元素,并将根元素添加为 //文件内容。 root.addContent(child); document.setContent(root); //用漂亮的格式化程序创建一个XMLOutputter对象。呼唤 //outputString(Documentdoc)方法转换文档 //转换为字符串数据。 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); String xmlString = outputter.outputString(document); System.out.println(xmlString); } }
我们的代码片段的结果:
<?xml version="1.0" encoding="UTF-8"?> <rows> <row> <firstname>Alice</firstname> <lastname>Mallory</lastname> <address>Sunset Road</address> </row> </rows>
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency>