package anby.com; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.dom4j.io.SAXWriter; import org.dom4j.io.XMLWriter; import org.xml.sax.SAXException; public class Dom4jCUD { /** * @param args */ public static void main(String[] args)throws Exception { Document doc= readXml("Book.xml"); //使用 Xpath进行查询 Node node= doc.selectSingleNode("//book[@id='boo1']"); Element ele=(Element)node; //获取元素内容 Element titileEle=ele.element("titile"); System.out.println(ele.elementText("titile")); //修改元素内容 titileEle.setText("孔乙己"); System.out.println(ele.elementText("titile")); //删除元素 Node bookNode=doc.selectSingleNode("//book[@id='boo2']"); Element Parent=bookNode.getParent();//获取父节点 Parent.remove(bookNode); //创建元素 Element root=doc.getRootElement(); Element newbook=DocumentHelper.createElement("book"); Attribute subTiltle= DocumentHelper.createAttribute(newbook, "id", "boo3"); newbook.addAttribute("id", "boo3");//增加属性 //创建子元素 Element subTiltle1= DocumentHelper.createElement("titile"); subTiltle1.setText("孔乙己"); newbook.add(subTiltle1); //父元素增加子元素 Element subPrice= DocumentHelper.createElement("price"); subPrice.setText("30"); newbook.add(subPrice); //父元素增加子元素 root.add(newbook);//父节点增加book、节点 //格式不规范,需要格式化xml,还有出现中文乱码现象 saveXml(doc); } public static Document readXml(String path) throws DocumentException { SAXReader saxreader =new SAXReader(); return saxreader.read(new File(path)); } public static void saveXml(Document document) throws SAXException, IOException { XMLWriter writer=new XMLWriter(new FileWriter("Books.xml")); writer.write(document); writer.close(); } }