您的位置:首页 > 其它

JDOM操作XML简单示例

2008-05-24 00:58 549 查看
google_ad_client = "pub-8800625213955058";

/* 336x280, 创建于 07-11-21 */

google_ad_slot = "0989131976";

google_ad_width = 336;

google_ad_height = 280;

//

JAVA语言的开放性,吸引了很多公司和个人作者对JAVA的性能作不断地完善。JDOM 是两位著名的 Java 开发人员兼作者,Brett Mclaughlin 和 Jason Hunter 的创作成果,它致力于建立一个完整的基于 Java 平台的解决方案,通过 Java 代码来访问、操作并输出 XML 数据。

JDOM可以从http://jdom.com网站上下载,目前最新的版本是beta9.0。

一、用JDOM建立XML文档

我们想建立一个形如下文的XML文档:1.xml

<?xml version=”1.0” encoding=”gb2312”?>

<个人资料>

<姓名 ID号=”2222”>张二</姓名>

<年龄>20</年龄>

</个人资料>

我们先建立一个根元素和文档的实例,将根元素加入到文档中:

Element root=new Element(“个人资料”);

Document doc=new Document(root);

加入子元素:

Element name=new Element(“姓名”);

Name.setAttribute(new Attribute(“ID号”,”2222”));

Name.addContent(“张二”);

Root.addContent(name);

Element age=new Element(“年龄”);

Age.addContent(“20”);

Root.addContent(age);

因为addContent()方法返回值为Element类型,上面的代码也可以写成:

root.addContent(new Element("姓名").addContent("张二").setAttribute("ID号","2222"));

root.addContent(new Element("年龄").addContent("20"));

使用FileOutputStream,生成XML文本

try

{

String ident=” ”; //子元素缩进两个空格

Boolean isNew=true; //元素间有空行

String cset=”gb2312”; //编码,显示中文

XMLOutputter outer=new XMLOutputter(“ “,true,cset);

Outer.output(doc.new FileOutputStream(“1.xml”));

}catch(IOException e)

{

e.printStackTrace();

}

通过上面的代码,我们就生成了,如上所示的xml页面。

从1.xml中取得相应的值:

使用 SAXBuilder 对 1.xml进行语法分析

try

{

SAXBuilder sb=new SAXBuilder();

Document myDoc=sb.build(new FileInputStream(“1.xml”));

}catch(JDOMException e)

{

e.printStackTrace();

}catch(NullPointerException e)

{

e.printStackTrace();

}

访问子元素

Element another=myDoc.getRootElement(); //先得到根元素

Element nameE=root.getChild(“姓名”);

System.out.println(nameE.getText());

删除子元素

boolean re=another.removeChild(“姓名”);

//删除后,记得将文档重新写入一遍
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: