Dom4j生成XML文件,并解决乱码问题
上次写过一段JDOM生成XML文件的例子(文章在这里),其实java操作xml文件还能用dom4j。
首先要下载DOM4J的jar包,可以去DOM4J的官网去下,地址是www.dom4j.org,如果会翻墙的也可以去sourceforge下载
package com.havenliu.blog; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Dom4jXmlOper { public static void createXml(File file) { XMLWriter writer = null; SAXReader reader = new SAXReader(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8");//设置XML文件的编码格式,如果有中文可设置为GBK或UTF-8 Document _document = DocumentHelper.createDocument(); Element _root = _document.addElement("userinfo"); Element user = _root.addElement("user"); user.addAttribute("id", "001"); Element name = user.addElement("name"); name.setText("张三"); Element age = user.addElement("age"); age.setText("28"); Element sex = user.addElement("sex"); sex.setText("男"); Element email = user.addElement("email"); email.setText("abc@abc.com"); //如果上面设置的xml编码类型为GBK,则应当用FileWriter来构建xml文件,否则会出现中文连码问题 /* try { writer = new XMLWriter(new FileWriter(file), format); } catch (IOException e1) { e1.printStackTrace(); } */ //如果上面设置的xml编码类型为utf-8,则应当用FileOutputStream来构建xml文件,否则还是会出现乱码问题 FileOutputStream fos = null; try { fos = new FileOutputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } try { writer = new XMLWriter(fos, format); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { writer.write(_document); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { String filePath = "d:\\temp\\user.xml";//生产的XML文件位置 File file = new File(filePath); Dom4jXmlOper.createXml(file); } } |
生成好以后的xml文件格式:
<?xml version="1.0" encoding="utf-8"?> <userinfo> <user id="001"> <name>张三</name> <age>28</age> <sex>男</sex> <email>abc@abc.com</email> </user> </userinfo> |
This entry was posted on 星期三, 七月 29th, 2009 at 8:25 上午 and is filed under Java. You can follow any responses to this entry through the RSS 2.0 feed.


























