码迷,mamicode.com
首页 > 编程语言 > 详细

java 生成xml 编码 utf-f 、 gb2312

时间:2014-11-30 15:35:37      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:xml   编码   

没有难度,直接上代码了

/**
	 * 
	 * @param fileName
	 */
	public static void createXmlUtf_8(String fileName) {

		Element root = DocumentHelper.createElement("root");
		Document document = DocumentHelper.createDocument(root);
		Element title = root.addElement("title");
		title.setText("标题");// 赋值

		try {// 写入文件
			FileWriter fileWriter = new FileWriter(fileName);
			OutputFormat format = new OutputFormat();
			XMLWriter xmlWriter = new XMLWriter(fileWriter, format);
			xmlWriter.write(document); // 写入文件中
			xmlWriter.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	/**
	 * 
	 * @param fileName
	 */
	public static void createXmlGb2312(String fileName) {
		Element root = DocumentHelper.createElement("root");
		Document document = DocumentHelper.createDocument(root);
		document.setXMLEncoding("gb2312");
		Element title = root.addElement("title");
		title.setText("标题");// 赋值

		try {// 写入文件
			 java.io.Writer wr=new java.io.OutputStreamWriter(new java.io.FileOutputStream(fileName),"gb2312");  
			 document.write(wr);  
			 wr.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

结果:

 <?xml version="1.0" encoding="UTF-8" ?> 
 <root>
  <title>标题</title> 
  </root>

<?xml version="1.0" encoding="gb2312" ?> 
 <root>
  <title>标题</title> 
  </root>



java 生成xml 编码 utf-f 、 gb2312

标签:xml   编码   

原文地址:http://blog.csdn.net/smile0198/article/details/41622557

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!