java生成xml文件不用dom

| 阅读数:--次| 作者:小豆豆
摘要:java用dom生成xml好麻烦,直接拼文本把后缀改成xml
java代码
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class Test {
	/**
	 * 写xml文件
	 * @param path 要存的路径
	 * @param context 要存的xml内容
	 * @param charsetname 以什么编码方式存
	 */
	public static void savexmlfile(String path,String context,String charsetname){
		if(path==null)return;
		if("".equals(path))return;
		if(charsetname==null || "".equals(charsetname))charsetname="UTF-8";
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(path);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		OutputStreamWriter osw=null;
		try {
			osw = new OutputStreamWriter(fos,charsetname);
		} catch (UnsupportedEncodingException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} 
		BufferedWriter bw=new BufferedWriter(osw); 
		try {
			bw.append(context);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		try {
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		StringBuffer sb=new StringBuffer();
		sb.append("<?xml version='1.0' encoding='utf-8' standalone='no' ?>");
		sb.append("<root>");
		sb.append("<section name='胡夏' id='1'>");
		sb.append("<Piclist id='1' img='图片地址' title='标题' desc='介绍'/>");
		sb.append("</section>");
		sb.append("</root>");
		savexmlfile("f:\\b.xml", sb.toString(), "UTF-8");
		System.out.println("run end:www.webkfa.com");
	}
}
返回顶部
学到老代码浏览 关闭浏览