欢迎来到天天文库
浏览记录
ID:40557759
大小:22.91 KB
页数:6页
时间:2019-08-04
《jdom解析java》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、jdom解析xml (2010-05-2510:36:46)转载▼标签: jdom 解析 xml java分类: 技术摘要packagebean;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.util.List;importorg.j
2、dom.Document;importorg.jdom.Element;importorg.jdom.JDOMException;importorg.jdom.input.SAXBuilder;importorg.jdom.output.XMLOutputter;publicclassXmlParse{ //解析xml文件 publicstaticvoidXmlParse()throwsJDOMException,IOException{ SAXBuilderbuilder=newSAXBuilder(); InputStreamfile=newF
3、ileInputStream("src/xml/po.xml"); Documentdocument=builder.build(file);//获得文档对象 Elementroot=document.getRootElement();//获得根节点 Listlist=root.getChildren(); for(Elemente:list){ System.out.println("ID="+e.getAttributeValue("id")); System.out.println("username="+e.get
4、ChildText("username")); System.out.println("password="+e.getChildText("password")); } } //增 publicstaticvoidaddXml()throwsJDOMException,FileNotFoundException,IOException{ SAXBuilderbuilder=newSAXBuilder(); Documentdoc=builder.build("src/xml/po.xml");//获得文档对象 Elementroot=doc
5、.getRootElement();//获得根节点 //添加新元素 Elementelement=newElement("person"); element.setAttribute("id","3"); Elementelement1=newElement("username"); element1.setText("zhangdaihao"); Elementelement2=newElement("password"); element2.setText("mima"); element.addContent(element1);
6、 element.addContent(element2); root.addContent(element); doc.setRootElement(root); //文件处理 XMLOutputterout=newXMLOutputter(); out.output(doc,newFileOutputStream("src/xml/po.xml")); } //根据ID值删除一个节点 publicstaticvoiddeletePerson(intid)throwsJDOMException,IOException{ SAXBuil
7、derbuilder=newSAXBuilder(); InputStreamfile=newFileInputStream("src/xml/po.xml"); Documentdoc=builder.build(file);//获得文档对象 Elementroot=doc.getRootElement();//获得根节点 Listlist=root.getChildren(); for(Elemente:list){ //获取ID值 if(Integer.parseInt(e.getAttributeValue("i
8、d"))==id){ root.removeContent(
此文档下载收益归作者所有