在网上经常会有人在百度知道中文,怎样使用Dom4j删除一个节点,其实我在前面几篇文章中已经讲解了,这里单点拿出来说一下,方便又需要的朋友参考。下面是我们要操作的XML文档结构,如下:
<?xml version="1.0" encoding="UTF-8" ?> <root> <node1 show="yes" name="sample" data="01"> <title>Dom4j Tutorials</title> <owner>O'Reilly</owner> <node1-01 name="sample-01" date="01-01" /> <node1-01 name="sample-02" date="01-02" /> <node1-01 name="sample-03" date="01-03" /> <node1-01 name="sample-04" date="01-04" /> <node1-01 name="sample-05" date="01-05" /> </node1> </root>
问题:
在上面的代码中如何根据节点的name 来删除节点啊,比如要删除name="sample-01"的节点,望高手赐教!
解答:
Document doc = DocumentHelper.createDocument();
Element scohool = doc.addElement("school");
scohool.addElement("teacher").addComment("this is a 优秀的老师").addAttribute("age","33").addAttribute("face","帅").setText("老吴");
Element ele = scohool.addElement("haha");
ele.addElement("node1-01").addAttribute("name", "11");
ele.addElement("node1-01").addAttribute("name", "12");
ele.addElement("node1-01").addAttribute("name", "13");
ele.addElement("node1-01").addAttribute("name", "14");
ele.addElement("node1-01").addAttribute("name", "15");
List list = ele.elements();
for (int i = 0; i < list.size(); i++) {
    Element e = (Element)list.get(i);
    String value = e.attributeValue("name",null);
    if("14".equals(value)){
        ele.remove(e);
    }
}
try {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("GB2312");
    XMLWriter out = new XMLWriter(new FileOutputStream("e:/1.xml"),format);
    out.write(doc);
    out.close();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}上面是通过一个迭代,判断name为指定的值则将该元素删除掉,然后将修改后的文档输出到1.xml文档中。
