二、DOM4J解析
使用DOM4J要先导一个jar包,可以去官网下载
目的一:将以下的XML文件通过解析用JAVA语言在控制台上输出
<?xml version="1.0" encoding="UTF-8"?> <books> <book> <title>三国演义</title> <author>罗贯中</author> <price>30元</price> </book> <book> <title>水浒传</title> <author>施耐庵</author> <price currencu="renminbi">35元</price> </book> <book> <title>西游记</title> <author>吴承恩</author> <price>85</price> </book> </books>
先获得解析器
//获取解析器 SAXReader saxReader=new SAXReader();
获得Document对象
//获得Document对象 Document document=saxReader.read(new File("E:\\IJ\\src\\XMLAdditional/Book.xml"));
DOM4J中,Document中有一个方法可以得到跟元素
//得到跟元素 Element first=document.getRootElement();
根据根元素,进行操作,得到根元素下一个节点的元素
//得到根元素下的第二节点,是一个迭代器 Iterator second=first.elementIterator();
然后进行遍历,得到第二节点的元素
然后在遍历中将单个第二节点元素看成根元素,接着上面的操作,知道得到最后一个节点的内容的迭代器
//遍历得到所有的第二节点,也就是所有的book while (second.hasNext()){ //得到当前第二节点对应的第三节点 Element element=(Element) second.next(); //遍历得到第三节点的内容 Iterator third=element.elementIterator(); //遍历得到所有的第三节点,也就是title,autor,price while (third.hasNext()){ Element ele=(Element) third.next(); if(ele.getName().equals("price")){ Attribute attribute=ele.attribute("currencu"); if(attribute!=null){ System.out.println(attribute.getValue()); } } System.out.println(ele.getText()); } System.out.println("************************************************"); }
目的一完成,能显示出三本书的信息
目的二:添加一本书,红楼梦,曹雪芹,63
在根元素基础下一节一节的加上去
Element first=document.getRootElement(); //创建第二节点 Element book=first.addElement("book"); //创建第三节点 Element title=book.addElement("title"); Element author=book.addElement("author"); Element price=book.addElement("price"); //创建第四节点 title.setText("红楼梦"); author.setText("曹雪芹"); price.setText("63");
目的二完成,但是没有保存在XML文件中
目的三:保存在XML中
OutputFormat format=OutputFormat.createPrettyPrint();//用OutputFormat,不能直接new format.setEncoding("UTF-8");//设置编码格式 try { XMLWriter writer=new XMLWriter(new FileWriter("E:\\IJ\\src\\XMLAdditional/Book.xml"),format); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); }至此,目的三完成。