Jdom生成xml文件

public static void updateXML(String filePath) throws Exception {
		SAXBuilder sb = new SAXBuilder();
		Document doc = sb.build(new FileInputStream(filePath));//读入文件
		Element root = doc.getRootElement(); //获得根元素
//		Element e = root.getChild("occupation");
//		System.out.println(e.getText());
//		System.out.println(e.getName());
//		System.out.println(e.getAttributeValue("dynasty"));//获取元素属性值
		
//		e.setText("大皇帝");
		
		List li = root.getContent();//所有内容:子元素、注释、文本等
		List list = root.getChildren(); //只有标记内容
		System.out.println(li.size());
		System.out.println(list.size());
		
		Element ele = (Element) list.get(0);
		System.out.println(ele.getText());
		//将doc写入到某一个xml文件中,从而更新硬盘中的文件
//		XMLOutputter xmlOut = new XMLOutputter();
//		xmlOut.output(doc, new FileOutputStream(filePath));
	}



//需要导入jdom.jar包
public static void createXML() throws Exception {
		Element root = new Element("resume");
		Element name = new Element("name");
		Element preName = new Element("preName");
		Element occupation = new Element("occupation");
		Element preOccupation = new Element("preOccupation");
		
		Attribute attr = new Attribute("dynasty", "唐朝");
		occupation.setAttribute(attr);
		
		name.setText("李世明");
		preName.addContent("秦王");
		preOccupation.addContent("将军");
		occupation.addContent("皇帝");
		
		root.addContent(name);
		root.addContent(preName);
		root.addContent(occupation);
		root.addContent(preOccupation);
		
		Document doc = new Document(root);
		Format format = Format.getPrettyFormat();
		//Format format = Format.getCompactFormat();
		format.setEncoding("utf-8");  //<?xml version="1.0" encoding="utf-8"?>
		XMLOutputter xmlOutputter = new XMLOutputter(format);
		xmlOutputter.output(doc, new FileOutputStream("f:/1.xml"));
	}



转载于:https://my.oschina.net/u/1413786/blog/180538

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值