转自:
Java如何使用dom4j获取,添加,删除,查找,设置Element节点呢?
下文笔者讲述DOM4J操作Element节点的示例分享,如下所示
Element rootElm = document.getRootElement();
Element memberElm=root.element("user");// "user"是节点名
String text=memberElm.getText();//也可以用: String text=root.elementText("name");//这个是取得根节点下的name字节点的文字.
List nodes = rootElm.elements("user"); for (Iterator it = nodes.iterator(); it.hasNext();) { Element elm = (Element) it.next(); //运行业务代码 }
for(Iterator it=root.elementIterator();it.hasNext();){ Element element = (Element) it.next(); //业务代码 }
Element ageElm = newMemberElm.addElement("age");
ageElm.setText("88");
parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点
Element contentElm = infoElm.addElement("content"); contentElm.addCDATA(diary.getContent());
例
public void modifyDoc() { try { Document doc = reader.read(new File("file/test.xml")); //修改节点内容 List list = doc.selectNodes("//user"); Iteratorit = list.iterator(); while (it.hasNext()) { Element el = it.next(); fail(el.getName() + "#" + el.getText() + "#" + el.getStringValue()); //修改title元素 Iterator 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("//user/author"); it = list.iterator(); while (it.hasNext()) { Element el = it.next(); fail(el.getName() + "#" + el.getText() + "#" + el.getStringValue()); List 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/test.xml"))); output.write(doc); output.close();*/ } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }