Dom4j复制节点到指定节点下的Demo

public static void main(String[] args) throws DocumentException,IOException {
		String xml = "" 
				+ ""
				+ "c1" 
				+ "" + "c2" + "" 
				+ "c3"
				+ "" 
				+ "";

		Document document = DocumentHelper.parseText(xml.toString());
		Element rootElement = document.getRootElement();
		Element elementToAdd = (Element) rootElement.selectSingleNode("//bbb/ccc[2]");
		Element bElement = (Element) document.selectSingleNode("//bbb");
		List cList = bElement.elements();
		cList.add(2, (Element) elementToAdd.clone());

		// XML格式化
		StringWriter stringWriter = new StringWriter();
		OutputFormat xmlFormat = OutputFormat.createPrettyPrint();// 紧凑格式,无空格换行
		xmlFormat.setEncoding("UTF-8");
		xmlFormat.setNewlines(true);
		xmlFormat.setIndent(true);
		xmlFormat.setIndent("    ");
		XMLWriter xmlWriter = new XMLWriter(stringWriter, xmlFormat);
		xmlWriter.write(document);
		xmlWriter.close();
		System.out.println(stringWriter.toString());

	}

控制台输出如下:




    
        c1
        
            
                c2
            
        
        
            
                c2
            
        
        c3
    

可见,c2节点为新增节点。

你可能感兴趣的:(工具&框架,Dom4j)