求大神给写个xml合并的demo 需求是这样的
xml1
- XML code
<root> <info> <name>华为</name> </info> <info> <name>ibm</name> </info></root>
xml2
- XML code
<root> <info> <url>www.huawei.com</url> </info> <info> <url>www.ibm.com</url> </info></root>
合并成新的xml
- XML code
<root> <info> <name>华为</name> <url>www.huawei.com</url> </info> <info> <name>ibm</name> <url>www.ibm.com</url> </info></root>
------解决方案--------------------
列子:
http://ghostfromheaven.iteye.com/blog/762155
其实仔细看api帮助,慢慢学习能写出来的。
------解决方案--------------------
给你写个例子,参考下吧。很容易,楼主可以自己修改处理更复杂的
- Java code
import java.io.File;import java.io.FileOutputStream;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class XMLCom{ public static void main(String[] args) { SAXReader reader = new SAXReader(); File file = new File("d:\\test.xml"); File file1 = new File("d:\\test1.xml"); try { Document document = reader.read(file); Document document1 = reader.read(file1); List<Element> infos = document.selectNodes("root/info"); List<Element> infos1 = document1.selectNodes("root/info"); for(int i = 0;i < infos.size();i++){ Element info = infos.get(i); Element info1 = infos1.get(i); List<Element> ls = info1.elements(); Element add = (Element)ls.get(0).clone(); info.add(add); } OutputFormat format = new OutputFormat(); format = OutputFormat.createPrettyPrint(); XMLWriter output = null; output = new XMLWriter(new FileOutputStream(new File("d://comtest.xml")), format); output.write(document); output.close(); }catch(Exception e){ e.printStackTrace(); } }}