http://www.51gjie.com/java/743.html
Java dom4j获取,添加,删除,查找,设置Element节点方法
1.获取文档的根节点.
Element rootElm = document.getRootElement();
2.取得某节点的单个子节点.
Element memberElm=root.element("member");// "member"是节点名
3.取得节点的文字
String text=memberElm.getText();//也可以用: String text=root.elementText("name");//这个是取得根节点下的name字节点的文字.
4.取得某节点下名为"member"的所有字节点并进行遍历.
List nodes = rootElm.elements("member"); for (Iterator it = nodes.iterator(); it.hasNext();) { Element elm = (Element) it.next(); // do something }
5.对某节点下的所有子节点进行遍历.
for(Iterator it=root.elementIterator();it.hasNext();){ Element element = (Element) it.next(); // do something }
6.在某节点下添加子节点.
Element ageElm = newMemberElm.addElement("age");
7.设置节点文字.
ageElm.setText("29");
8.删除某节点.
parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点
9.添加一个CDATA节点.
Element contentElm = infoElm.addElement("content"); contentElm.addCDATA(diary.getContent());
例子
public void modifyDoc() { try { Document doc = reader.read(new File("file/catalog.xml")); //修改节点内容 List list = doc.selectNodes("//article"); Iterator<Element> it = list.iterator(); while (it.hasNext()) { Element el = it.next(); fail(el.getName() + "#" + el.getText() + "#" + el.getStringValue()); //修改title元素 Iterator<Element> elIter = el.elementIterator("title"); while(elIter.hasNext()) { Element titleEl = elIter.next(); fail(titleEl.getName() + "#" + titleEl.getText() + "#" + titleEl.getStringValue()); if ("Java configuration with XML Schema".equals(titleEl.getTextTrim())) { //修改元素文本值 titleEl.setText("Modify the Java configuration with XML Schema"); fail(titleEl.getName() + "#" + titleEl.getText() + "#" + titleEl.getStringValue()); } } } //修改节点子元素内容 list = doc.selectNodes("//article/author"); it = list.iterator(); while (it.hasNext()) { Element el = it.next(); fail(el.getName() + "#" + el.getText() + "#" + el.getStringValue()); List<Element> childs = el.elements(); for (Element e : childs) { fail(e.getName() + "#" + e.getText() + "#" + e.getStringValue()); if ("Marcello".equals(e.getTextTrim())) { e.setText("Ayesha"); } else if ("Vitaletti".equals(e.getTextTrim())) { e.setText("Malik"); } fail(e.getName() + "#" + e.getText() + "#" + e.getStringValue()); } } //写入到文件 /*XMLWriter output = new XMLWriter(new FileWriter(new File("file/catalog-modified.xml"))); output.write(doc); output.close();*/ } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }