JAVA dom4j实现String字符串转换成XML文件(解决中文乱码问题)

首先导入需要用到的jar:

 
        
          dom4j
          dom4j
          1.6.1
        
	

java代码如下:

package com.accord.test;
 
import java.io.*; 
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
 
public class TestStringToXml {
	public static void main(String[] args) throws Exception {
		String content = "需要转换的xml字符串" ;
		String filename = "生成的xml文件自定义存放位置" ;
		Document document = DocumentHelper.parseText(content );
		exportXml(document,filename);
	}
	public static void exportXml(Document document,String filename){
		   OutputFormat format = OutputFormat.createPrettyPrint();
	       /** 指定XML编码 */
	       format.setEncoding("UTF-8");
	       /** 将document中的内容写入文件中 */
	       XMLWriter writer;
		try {
			OutputStream outputStream = new FileOutputStream(filename);
			writer = new XMLWriter(new OutputStreamWriter(outputStream ,"UTF-8"), format);
			writer.write(document);
		    writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	   }
}

同时附上一个在线xml字符串格式转换工具,相当好用:xml转换直达

你可能感兴趣的:(JAVA后端)