java生成xml

java生成xml文件例子(dom4j)


急着要用,先生成一个很low的Demo,想了想,还是留下点笔记吧。

代码:

package com.ywx.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;

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


public class XmlImpl {
	public static void main(String[] args) {
		try {
			XmlTest.createXml("");//保留参数,此处我是生成一个例子,打算在用时传入对象。
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
class XmlTest{
	private static Document doc = DocumentHelper.createDocument();
	public static void createXml(String fileName) throws Exception{
		Element share = doc.addElement("share");
		Element apply = share.addElement("apply");
		Element code = share.addElement("code");
		
		Element id = apply.addElement("id");
		Element name = apply.addElement("name");
		Element type = apply.addElement("type");
		Element num = apply.addElement("num");
		id.setText("123");
		name.setText("vashon");
		type.setText("行政");
		num.setText("56");
		
		Element ide = code.addElement("ide");
		Element name1 = code.addElement("name1");
		Element type1 = code.addElement("type1");
		Element num1 = code.addElement("num1");
		ide.setText("231");
		name1.setText("王五");
		type1.setText("材料Test");
		num1.setText("76");
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("GBK");
		XMLWriter writer = new XMLWriter(new FileOutputStream(new File("d:" + File.separator + "output.xml")),format);//输出路径
        writer.write(doc);
        writer.close();
	}
}</span>



运行结果截图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值