element.detach()与elment.appendContent(childEl.getParent())

public static void main( String[] args ){
	XMLReadandWrite mR = new XMLReadandWrite();
	
	try {
		Document document1 = mR.readXMLToDoc("test1.xml");
		Document document2 = mR.readXMLToDoc("test2.xml");
		List items = document1.selectNodes("//root//student");
		Document newDOc = DocumentHelper.createDocument();
		Element root = newDOc.addElement("root");
		for (Iterator iter = items.iterator(); iter.hasNext();) { 
			Element item = (Element) iter.next();
			//如果无需保留原文档对象 
			//root.add(item.detach());
			//System.out.println(item);
			//如果必需保留原对象
			root.appendContent(item.getParent()); 
		}
		List attr_listList = newDOc.selectNodes("//root//stdent//test");
		for(Object o:attr_listList){
			Element element = (Element)o;
			Attribute a = element.attribute("Name");
			//System.out.println(a.asXML());
			a.setValue("test");
			//System.out.println(a.asXML());
		}
		document2.getRootElement().appendContent(newDOc.getRootElement());
		document2.getRootElement().elements().add(0, (Element)newDOc.selectSingleNode("//root//student").clone());
		System.out.println(document2.asXML());
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}

 

 

 

 

 

你可能感兴趣的:(Java)