JDOM创建XML例子

如果不为其设置,将会默认编码为utf-8,并且不会换行等,生成的XML就会不美观,在网上搜索了,原到有采用这样设置编码的:
Document doc = new Document(); //内存中已构造好的jdom Document对象 
XMLOutputter output = new XMLOutputter(2, true, "GB2312"); //2是指缩进2个字符,true表示用换行,--增强可读性
FileOutputStream out = new FileOutputStream(fileName);
output.output(doc, out);

这是JDOM1.0以前支持的设置编码方法,以后的版本就没有了,JDOM已经将这一块功能给剥离出来,形成了Format对象,所有的设置都在该类当中处理,如下:
XMLOutputter out;     
Format format = Format.getCompactFormat();
format.setEncoding("gb2312"); //setEncoding就是设置编码了
format.setIndent(" "); //setIndent是设置分隔附的意思,一般都是用空格,就是当你新节点后,自动换行并缩进,有层次感,如果这样写setIndent(""),就只有换行功能,而不会缩进了,如果写成setIndent(null),这样就即不换行也不缩进,全部以一行显示了,默认的就是这样的效果,不好看。
out = new XMLOutputter(format);
out.output(xmlDoc, new FileOutputStream("xml文件路径"));

完整的JDOM创建XML文件代码如下:
package com.star.jdbc; 

import java.io.FileOutputStream;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.Text;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import junit.framework.TestCase;

public class TestXML extends TestCase {

public void testCreate(){
try{
Document doc = new Document();

Namespace ns = Namespace.getNamespace("http://www.bromon.org");
Namespace ns2 = Namespace.getNamespace("other", "http://www.w3c.org");

Element root = new Element("根元素", ns);
root.addNamespaceDeclaration(ns2);
doc.setRootElement(root);

Element el1 = new Element("元素一");
el1.setAttribute("属性", "属性一");
Text text1 = new Text("元素值");

Element em = new Element("元素二").addContent("第二个元素");
el1.addContent(text1);
el1.addContent(em);

Element el2 = new Element("元素三").addContent("第三个元素");

root.addContent(el1);
root.addContent(el2);

XMLOutputter outputter = null;
Format format = Format.getCompactFormat();
format.setEncoding("GB2312");
format.setIndent(" ");
outputter = new XMLOutputter(format);

outputter.output(doc, new FileOutputStream("C:\\a.xml"));
}catch(Exception e){
e.printStackTrace();
}
}
}

当用JDK自带的解析器来解析XML文件时,DocumentBuilder的parse()方法接收一个XML文档名作为输入参数,返回一个Document对象,这个Document对象就代表了一个XML文档的树模型。以后所有的对XML文档的操作,都与解析器无关,直接在这个Document对象上进行操作就可以了。
提示:如果XML文件是放在当前WEB应用的"WEB-INF/classes"目录下时,则在读取XML文件前要设置parse()方法中的参数,如本例在parse()方法中设置的参数为:this.getClass().getResourceAsStream("/user.xml");这种方法安全性较好,因为WEB-INF目录是客户端无法访问的文件夹。如果XML文件是放在与JSP文件同一目录中,则参数应改为:pageContext.getServletContext().getRerouceAsStream("/user.xml");。提倡使用前一种方法。

转自:[url]http://gang4415.blog.51cto.com/225775/248714/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值