Posted on 2006-07-04 22:21
dingdaiyang 阅读(109)
评论(0) 编辑 收藏 所属分类:
XML
JAVA操作XML的方式基本上有三种:
1.SAX: Simple API for XML
http://www.saxproject.org/
2. DOM: Document Object Model
http://www.w3.org/DOM
3. JDOM
O’Reilly两位作家开发的针对Java的XML解析包
http://www.jdom.org
前两种用起来比较麻烦,下面是用JDOM操作XML的主要代码:
一.采用JDom读取XML文件
//与SAX配合使用
SAXBuilder sax = new SAXBuilder();
//读取XML文件,构建Document对象
Document doc = sax.build("test.xml");
//获取根元素
Element root = doc.getRootElement();
//获取根元素下的子元素
List list = root.getChildren();
二.采用JDom写入XML文件
Document doc = new Document();
//创建根元素students
Element root = new Element("students");
Element s1 = new Element("student");
Element s2 = new Element("student");
root.addContent(s1);
root.addContent(s2);
//////////////////////////////////////
Element n1 = new Element("name");
Element sc1 = new Element("score");
s1.addContent(n1);
s1.addContent(sc1);
n1.setText("张三");
sc1.setText("80");
s1.setAttribute("id", "101");
s1.setAttribute("sex", "男");
///////////////////////////////////////
Element n2 = new Element("name");
Element sc2 = new Element("score");
Comment c = new Comment("因为作弊被发现,扣除10分");
s2.addContent(n2);
s2.addContent(c);
s2.addContent(sc2);
n2.setText("李四");
sc2.setText("40");
s2.setAttribute("id", "102");
doc.addContent(root);
////////////////////////////////////
XMLOutputter xmlOut = new XMLOutputter();
xmlOut.setFormat(Format.getPrettyFormat());
try {
xmlOut.output(doc, new FileOutputStream("test.xml"));
} catch (IOException ex) {
ex.printStackTrace();
}
////////////////////////////////////
刚开始学习XML,有总结不当之处,请指出.