java中用jdom写xml,JAVA 读写XML(1) 使用(JDOM)

本文介绍了如何使用Java和JDOM库创建和写入XML文件,包括创建Document对象、设置根元素、添加和修改元素属性及内容,最后演示了如何将XML写入到本地文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA 读写XML(一) 使用(JDOM)

使用java jdom 写xml文件

public void writeXml(){

Document doc=new Document();

Element root=new Element("Actors");

doc.setRootElement(root);

Element employee=new Element("Actress");

employee.addContent(new Element("id").setText("001"));

employee.addContent(new Element("name").setText("李冰冰"));

employee.addContent(new Element("sex").setText("女"));

employee.addContent(new Element("occupation").setText("演员"));

root.addContent(employee);

employee=new Element("Actress");

employee.setAttribute("id", "002");

employee.addContent(new Element("name").setText("周迅"));

employee.addContent(new Element("sex").setText("女"));

employee.addContent(new Element("occupation").setText("演员")).setAttribute("secoccupation", "歌手");

root.addContent(employee);

Element male=new Element("Actor");

Element actor=new Element("actor");

//actor.addContent("id").setText("003");

actor.setAttribute("id", "003");

actor.addContent(new Element("name").setText("张涵予"));

actor.addContent(new Element("occupation").setText("演员"));

male.addContent(actor);

actor=new Element("actor");

actor.setAttribute("id", "004");

actor.addContent(new Element("name").setText("黄晓明"));

actor.addContent(new Element("occupation").setText("演员")).setAttribute("secoccupation", "歌手");

male.addContent(actor);

root.addContent(male);

try {

XMLOutputter out=new XMLOutputter(Format.getPrettyFormat());

//out.output(doc, new FileWriter(new File("e:\\wind.xml")));

out.output(doc, new FileOutputStream(new File("e:\\wind.xml")));

} catch (Exception e) {

System.out.println("异常发生了!");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值