jdom解析xml
package domtest; import java.io.IOException; import org.jdom.Attribute; import org.jdom.Content; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.jdom.input.SAXBuilder; import java.util.List; import java.util.Iterator; import java.io.FileOutputStream; import org.jdom.JDOMException; public class DomTest { public DomTest() { String xmlpath = "src/book.xml"; //路径一定要注意(以你放的路径) SAXBuilder builder = new SAXBuilder(false); //使用JDOM首先要指定使用什么解析器,这表示使用的是默认的解析器 try { Document doc = builder.build(xmlpath); //得到Document Element books = doc.getRootElement(); //得到根元素 List booklist = books.getChildren("book"); //得到元素(节点)的集合 for (Iterator iter = booklist.iterator(); iter.hasNext(); ) { //循环节点集合 Element book = (Element) iter.next(); String email = book.getAttributeValue("email");//取得元素book的属性名为“email”的属性值。 System.out.println("邮箱===" + email); String name = book.getChildText("name");//取得元素的子元素的值 System.out.println("用户名===" + name); String price = book.getChildText("price"); System.out.println("价格=="+price); book.getChild("name").setText("李三"); //设置元素的值 book.getAttribute("email").setValue("[email protected]"); //设置元素属性的值 } //另外一程循环的的方法(解析xml文件后存入数据库的操作) // XmlBean xbean = null; // List list = new ArrayList(); // for(int i=0;i<booklist.size();i++){ // xbean = new XmlBean(); // Element book=(Element)booklist.get(i); // xbean.setEmail(book.getAttributeValue("email")); // xbean.setUsrename(book.getChildText("name")); // xbean.setPrice(book.getChildText("price")); // list.add(xbean); // } //保存Document的修改到XML文件中 XMLOutputter outputter = new XMLOutputter(); outputter.output(doc, new FileOutputStream(xmlpath)); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new DomTest();//测试上面所写的 } }
相关推荐
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
XGQ 2020-07-04
Andrewjdw 2020-05-29
Yakamoz 2020-05-26
行吟阁 2020-05-18
88491874 2020-04-30
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16