Java——JDOM方式生成XML

来源:互联网 发布:杰科网络电视机顶盒r1 编辑:程序博客网 时间:2024/04/30 10:38

使用JDOM方式生成XML文件的步骤如下:

  1. 创建根节点
  2. 创建Document对象,并将根节点传入其构造方法中
  3. 创建子节点,使用setAttribute()方法为其设置属性,使用setText()方法为其设置节点内容
  4. 使用父节点的setContent()方法为其设置子节点
  5. 创建XMLOutputter对象
  6. 使用XMLOutputter对象的output()方法将Document转换成XML文件

下面给出代码:

package util;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.jdom2.CDATA;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.output.EscapeStrategy;import org.jdom2.output.Format;import org.jdom2.output.XMLOutputter;public class XMLUtils {    public void createXMLByJDOM(File dest) {        // 创建根节点        Element rss = new Element("rss");        // 为根节点设置属性        rss.setAttribute("version", "2.0");        // 创建Document对象,并为其设置根节点        Document document = new Document(rss);        Element channel = new Element("channel");        Element title = new Element("title");//      设置节点内容,使用此方法会自动对特殊符号进行转义//      title.setText("<![CDATA[上海移动互联网产业促进中心正式揭牌 ]]>");//      设置CDATA类型的节点内容,使用此方法会自动在内容两边加上CDATA的格式        CDATA cdata = new CDATA("上海移动互联网产业促进中心正式揭牌");        title.setContent(cdata);        channel.setContent(title);        rss.setContent(channel);        // 创建XMLOutputter对象        XMLOutputter outputter = new XMLOutputter();        try {//          方法一:创建Format对象(自动缩进、换行)            Format format = Format.getPrettyFormat();//          为XMLOutputter设置Format对象            outputter.setFormat(format);//          方法二:创建Format对象,并设置其换行//          Format format = Format.getCompactFormat();//          format.setIndent("");            // 将Document转换成XML            outputter.output(document, new FileOutputStream(dest));        } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

在使用JDOM生成XML时,可自行指定其输出格式,有两种方法可选。

方法一:

//方法一:创建Format对象(自动缩进、换行)Format format = Format.getPrettyFormat();//为XMLOutputter设置Format对象outputter.setFormat(format);

方法二:

//方法二:创建Format对象,并设置其换行Format format = Format.getCompactFormat();format.setIndent("");

JDOM也会自动将特殊符号进行转义。若内容为CDATA数据,可创建一个CDATA对象,再将该对象设为子节点即可。这样,特殊符号不会进行自动转义。

//设置CDATA类型的节点内容,使用此方法会自动在内容两边加上CDATA的格式CDATA cdata = new CDATA("上海移动互联网产业促进中心正式揭牌");title.setContent(cdata);
0 0
原创粉丝点击