JDOM生成XML文档的一般方法

时间:2023-03-09 22:40:20
JDOM生成XML文档的一般方法

由于DOM提供的生成XML的方法不够直观,而且要用到各种繁琐的注解,鉴于此可借助第三方库-----JDOM生成XML文档。具体操作方式如下:

import java.io.FileOutputStream;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter; public class JDomTest3
{
public static void main(String[] args) throws Exception
{
// 创建一个XML文档。其中方法允许访问根元素和文档类型和其他文档级别的信息。
Document document = new Document(); // 创建XML根元素。方法允许用户获取和操作它的子元素和内容,直接访问元素的文本内容,操纵它的属性可以管理命名空间。
// 获取NamespaceAware
// getNamespacesInScope()的详细信息,命名空间范围是什么以及它在是如何管理的,JDOM提供了具体的管理方法。
Element root = new Element("Employees"); // 给根元素设置属性和属性值,也可以设置命名空间等信息,相同的属性和命名空间将被覆盖。
root.setAttribute("city", "合肥").setAttribute("company", "科大讯飞"); // 将根元素追加到该XML文档的结尾。
document.addContent(root); // 创建根元素下的一个子元素
Element employee = new Element("employee"); // 创建子元素下的子元素
Element id = new Element("id"); // 创建子元素下的子元素
Element name = new Element("name"); // 给子元素添加内容
name.setText("emp1"); // 给子元素添加内容
id.setText("34"); // 将子子元素追加到子元素的结尾
employee.addContent(id); // 将子子元素追加到子元素的结尾
employee.addContent(name); // 将子元素追加到根元素的结尾
root.addContent(employee); // 将JDOM文档对象作为比特流输出到磁盘
XMLOutputter out = new XMLOutputter(); // 设置一个格式化的方法
Format format = Format.getPrettyFormat(); // 设置具体格式化的内容
format.setIndent(" "); // 将格式化的方法添加到输出流中
out.setFormat(format); // JDOM输出流依赖于javaIO流
out.output(document, new FileOutputStream("d:/employees.xml")); } }