以文本方式查看主题

-  中文XML论坛 - 专业的XML技术讨论区  (http://bbs.xml.org.cn/index.asp)
--  『 DOM/SAX/XPath 』  (http://bbs.xml.org.cn/list.asp?boardid=11)
----  如何用Jdom对xml文件进行节点的添加或者删除!  (http://bbs.xml.org.cn/dispbbs.asp?boardid=11&rootid=&id=20869)


--  作者:远走高飞
--  发布时间:8/3/2005 1:08:00 PM

--  如何用Jdom对xml文件进行节点的添加或者删除!
例如如下xml文档
<?xml version="1.0" encoding="gb2312"?>
<imb>
     <film>
           <name>男人的抉择</name>
           <actor>尼古拉斯.凯奇</actor>
           <filmType>爱情片</filmType>
           <fileType>rmvb</fileType>
           <intro>非常好看</intro>
           <time>2小时</time>
           <addTime>2005-8-2</addTime>
           <downLoad_url>http://upc.edu.cn/film/familyMan.rmvb<;/downLoad_url>
           <pic_url>upload/man.jpg</pic_url>
           <downLoad_times>520</downLoad_times>
     </film>
</imb>

操作之后为<?xml version="1.0" encoding="gb2312"?>
<imb>
     <film>
           <name>男人的抉择</name>
           <actor>尼古拉斯.凯奇</actor>
           <filmType>爱情片</filmType>
           <fileType>rmvb</fileType>
           <intro>非常好看</intro>
           <time>2小时</time>
           <addTime>2005-8-2</addTime>
           <downLoad_url>http://upc.edu.cn/film/familyMan.rmvb<;/downLoad_url>
           <pic_url>upload/man.jpg</pic_url>
           <downLoad_times>520</downLoad_times>
     </film>
     <film>
           <name>香草天空</name>
           <actor>汤姆.克鲁斯</actor>
           <filmType>爱情片</filmType>
           <fileType>rmvb</fileType>
           <intro>非常好看</intro>
           <time>2小时</time>
           <addTime>2005-8-2</addTime>
           <downLoad_url>http://upc.edu.cn/film/familyMan.rmvb<;/downLoad_url>
           <pic_url>upload/cao.jpg</pic_url>
           <downLoad_times>250</downLoad_times>
     </film>
</imb>


--  作者:lulu1979714
--  发布时间:9/6/2005 5:12:00 PM

--  
我也很关注啊
--  作者:allrr
--  发布时间:1/11/2007 1:36:00 PM

--  
FileInputStream fi = null;
FileOutputStream fo = null;
fi = new FileInputStream(path);//path为xml文件的fullpath
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement();
List films = root.getChildren();
Element newFilm = new Element();
Element newName = new Element();
newName.setText("name");
newFilm .addContent("香草天空");
...
films.add(newFilm );
Format format = Format.getPrettyFormat();
format.setIndent("  ");
format.setEncoding("utf-8");
XMLOutputter outp = new XMLOutputter(format);
fo = new FileOutputStream(path);
outp.output(doc, fo);
W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
109.375ms