首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

xml解析(超全)-(4)

2012-11-09 
xml解析(超全)---(四)?新增节点:SAXReader readnew SAXReader()??Document docnull??try {???docread

xml解析(超全)---(四)



?新增节点:
SAXReader read=new SAXReader();
??Document doc=null;
??try {
???doc=read.read(new File("d://student.xml"));
???//获取根节点
???Element root=doc.getRootElement();
???//增加class节点
???Element classele=root.addElement("class").addAttribute("name", "1");
???//增加class的第一个子节点(student id=1)
???Element studentele=classele.addElement("student");
???studentele.addAttribute("id", "1");
???studentele.addElement("name").addText("龙啊");
???studentele.addElement("age").addText("123");
???//增加class的第二个子节点(student id=2)
???Element studentele1=classele.addElement("student");
???studentele1.addAttribute("id", "2");
???studentele1.addElement("name").addText("帅啊");
???studentele1.addElement("age").addText("23");
???
???OutputFormat format=OutputFormat.createPrettyPrint();
???format.setEncoding("gb2312");
???format.setNewlines(true);
???format.setIndent("??? ");
???XMLWriter write=new XMLWriter(new FileWriter("d://student.xml"),format);
???write.write(doc);
???write.close();
???
???
???
??} catch (DocumentException e) {
???e.printStackTrace();
??} catch (IOException e) {
???e.printStackTrace();
??}
显示结果:

xml解析(超全)-(4)
?删除节点:
SAXReader read=new SAXReader();
??Document doc=null;
??try {
???doc=read.read(new File("d://student.xml"));
???Element root=doc.getRootElement();
???
???Element element=(Element) doc.selectSingleNode("//class[@name=2]/student[@id=2]");
???Element eleclass=(Element)doc.selectSingleNode("//class[@name=2]");
???System.out.println(element.elementText("name"));
//???root.remove(element);?? 错误
???eleclass.remove(element);
???
???OutputFormat format=OutputFormat.createPrettyPrint();
???format.setEncoding("gb2312");
???XMLWriter write=new XMLWriter(new FileWriter("d://student.xml"),format);
???write.write(doc);
???write.close();
???
??} catch (DocumentException e) {
???e.printStackTrace();
??} catch (IOException e) {
???e.printStackTrace();
??}
修改节点:
SAXReader read=new SAXReader();
??Document doc=null;
??try {
???doc=read.read(new File("d://student.xml"));
???Element root=doc.getRootElement();
???
???List list=doc.selectNodes("//class/student[@id=1]/age");
???for(Iterator it=list.iterator();it.hasNext();){
????Element element=(Element)it.next();
????element.setText("10");
???}
???OutputFormat format=OutputFormat.createPrettyPrint();
???format.setEncoding("gb2312");
???XMLWriter write=new XMLWriter(new FileWriter("d://student.xml"),format);
???write.write(doc);
???write.close();
???
??} catch (DocumentException e) {
???e.printStackTrace();
??} catch (IOException e) {
???e.printStackTrace();
??}

热点排行