在官网https://dom4j.github.io/下载最新的dom4j的jar包,以及配合xpath解析的http://central.maven.org/maven2/jaxen/jaxen/1.1.6/的jaxen.jar包。
总的来说其实要掌握的是,node和element和attribute的使用,以及一些迭代器配合。下面展示示例代码。具体演示了xml的增删改查的操作。
package Day04; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.junit.Test; public class XmlDemo { private void documentToFile(Document doucument,String charsetName) throws Exception { FileOutputStream fileWiter = new FileOutputStream("src/book.xml"); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new OutputStreamWriter(fileWiter,charsetName), format); writer.write( doucument ); writer.close(); } @Test public void CreateXml() { Document document = DocumentHelper.createDocument(); Element root = document.addElement("书店"); Element cateGrayElement1 = root.addElement("分类").addAttribute("descript", "童话故事"); Element cateGrayElement2 = root.addElement("分类").addAttribute("descript", "IT技术刊"); Element bookElement1 = cateGrayElement1.addElement("书"); bookElement1.addElement("书名").addText("格林童话"); bookElement1.addElement("国家").addText("非中"); Element bookElement2 = cateGrayElement1.addElement("书"); bookElement2.addElement("书名").addText("愚公移山"); bookElement2.addElement("国家").addText("中国"); Element bookElement3 = cateGrayElement2.addElement("书"); bookElement3.addElement("书名").addText("Tcp/ip 详解"); bookElement3.addElement("国家").addText("非中"); Element bookElement4 = cateGrayElement2.addElement("书"); bookElement4.addElement("书名").addText("c语言入门"); bookElement4.addElement("国家").addText("中国"); try { documentToFile(document,"UTF-8"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void treeWalk(Document document) { treeWalk(document.getRootElement()); } public void treeWalk(Element element) { for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); if (node instanceof Element) { String name = node.getName(); switch(name) { case "分类":System.out.println(name+"(descript="+((Element) node).attributeValue("descript")+")");break; case "书":System.out.println(" "+name);break; default:System.out.println(" "+name+" "+node.getText()); } treeWalk((Element) node); } else { // do something… } } } /* * 递归输出xml */ @Test public void loopXml() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read("src/book.xml"); treeWalk(document); } /** * 利用xpath语法 获取属性和节点 */ @Test public void xpath() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read("src/book.xml"); System.out.println("----------------------获取属性---------------------------------"); List<Node> attrlists = document.selectNodes("//@descript"); Iterator<Node> attrIt = attrlists.iterator(); while(attrIt.hasNext()) { Attribute attr = (Attribute)attrIt.next(); System.out.println("分类的"+(attr).getName()+"="+attr.getData()); } System.out.println("----------------------获取节点---------------------------------"); List<Node> lists = document.selectNodes("//书"); Iterator<Node> it = lists.iterator(); while(it.hasNext()) { //获取子类值 Node node = it.next(); for (Iterator<Element> bookIt = ((Element)node).elementIterator(); bookIt.hasNext();) { Element element = bookIt.next(); System.out.println(element.getName()+":"+element.getText()); // do something } } System.out.println("-----------------------获取属性的节点--------------------------------"); List<Node> attrlists1 = document.selectNodes("//分类[@descript="童话故事"]"); Iterator<Node> attrIt1 = attrlists1.iterator(); while(attrIt1.hasNext()) { //获取子类值 Element cateElement = (Element)attrIt1.next(); System.out.println(cateElement.getName()+"attributes:descript="+cateElement.attribute("descript").getValue()); } } /** * 演示插入,在愚公移山书名后加一个简介(指定位置插入) */ @Test public void insert() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read("src/book.xml"); //找到第二本书//分类[@descript="童话故事"]/书[2] Node pNode = document.selectSingleNode("//分类[@descript="童话故事"]/书[2]"); List<Element> list = ((Element)pNode).elements(); Element addNode = DocumentHelper.createElement("简介"); addNode.addText("《愚公移山》是战国时期思想家列子创作的一篇寓言小品文。文章叙述了愚公不畏艰难,坚持不懈,挖山不止,最终感动天帝而将山挪走的故事。"); list.add(1, addNode); System.out.println(list.toArray()); try { documentToFile(document,"UTF-8"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 修改xml元素 */ @Test public void update() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read("src/book.xml"); //找到要修改的节点,比如我现在想给愚公移山这个书名加上书名号 Node pNode = document.selectSingleNode("//分类[@descript="童话故事"]/书[2]/书名"); pNode.setText(new StringBuffer().append("《").append(pNode.getText()).append("》").toString()); try { documentToFile(document,"UTF-8"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 删除,刚刚添加的愚公移山的简介 */ @Test public void delete() throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read("src/book.xml"); //找到要修改的节点,比如我现在想给愚公移山这个书名加上书名号 Node pNode = document.selectSingleNode("//分类[@descript="童话故事"]/书[2]/简介"); ((Element)pNode).getParent().remove(pNode); try { documentToFile(document,"UTF-8"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }