把符合XML规定的字符串解析为XML文件

package cn.itcast.xml.parser.dom4j;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Demo3 {
	private static void writerToFile(Document document)throws Exception{
		//取得输出格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		//设置XML输出的编码方式
		format.setEncoding("UTF-8");
		//将内存中的字节转换成字符
		Writer writer = new OutputStreamWriter(new FileOutputStream("src/cn/itcast/xml/parser/dom4j/str.xml"),"UTF-8");
		//创建dom4j的输出字符流
		XMLWriter xmlWriter = new XMLWriter(writer,format);
		//真正输出
		xmlWriter.write(document);
		//关闭流
		xmlWriter.close();
	}
	public static void main(String[] args) throws Exception {
		String str = "<root><name>张三</name></root>";
		Document document = DocumentHelper.parseText(str);
		writerToFile(document);
	}
}

 

你可能感兴趣的:(java,xml)