首页 > Java

java生成xml文件不用dom

发表于2014-07-17 10:22:59| --次阅读| 来源webkfa| 作者小豆豆

摘要: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");
	}
}

相关文章

猜你喜欢

学到老在线代码浏览器 关闭浏览
友情链接: hao123 360导航 搜狗网址导航 114啦网址导航 博客大全
Copyright © 1999-2014, WEBKFA.COM, All Rights Reserved  京ICP备14034497号-1