dom4j插入节点到指定位置

  try { SAXReader reader = new SAXReader(); Document document = reader.read("src/resource/file.xml"); Element root = document.getRootElement(); List<Element> elements = root.elements(); int index = 0; for(Element element:elements){ index++; if("1".equals(element.attributeValue("id"))){ Element elem = DocumentHelper.createElement("chapter"); elem.addAttribute("id", "5"); elem.addAttribute("name", "e"); elements.add(index,elem); break; } } OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileWriter("src/resource/file.xml"),format); writer.write(document); writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }

 

你可能感兴趣的:(dom4j插入节点到指定位置)