import org.junit.Test; import java.util.List; /** * Created by dalei.qi on 2021/6/3. */ public class DocumentHelperUntil { @Test public void replace() throws DocumentException { String strtaeget = getxmlStrtaeget(); String strRplace = getxmlStrRplace(); Document targe = DocumentHelper.parseText(strtaeget); Document replace = DocumentHelper.parseText(strRplace); Element rootElement = replace.getRootElement(); //栓除/Application/RosterList的RosterList节点 Element rosterList = rootElement.element("RosterList").element("GreyList"); //获取根节点 Element targeRootElement = targe.getRootElement(); //得到Element的内容 List content = targeRootElement.content(); //添加节点content.add(rosterList); //制动位置 content.add(0,rosterList); //加载数据到原始节点 targeRootElement.setContent(content); System.out.println("after = "+ targe.asXML()); } public String getxmlStrtaeget() { return "\t<Application > \n" + "\t\t<RosterList>\n" + "\t\t<BlackList bLackStrategyID=\"-9981\" blackListLevel=\"-9981\" blackListLevelJXH=\"-9981\" blackListScoreJXH=\"-9981\" blackListSourceChannel=\"-9981\" blackListType=\"-9981\" blackReasonMsg=\"-9981\" blackSourceType=\"-9981\" isBlackCustomer=\"false\"/>\n" + "\t\t<GreyList greyReasonMsg=\"-9999\" greyStrategyID=\"-9999\" isGreyCustomer=\"-9999\"/>\n" + "\t</RosterList>\n" + "\t\n" + "\t</Application>"; } public String getxmlStrRplace() { return "<Application> \n" + "\t\t<RosterList>\n" + "\t\t<GreyList greyReasonMsg=\"-9999\" greyStrategyID=\"-9999\" isGreyCustomer=\"-9999\"/>\n" + "\t</RosterList>\n" + "\t\n" + "\t</Application>"; } }