如果不为其设置,将会默认编码为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();
- }
- }
- }