使用 JAVA 将标签从 xml 文件导入到另一个文件

Import Tag from xml file to another using JAVA

我用这块做我的工作,我的问题很简单。只是改变转移的地方。我不知道第一个或最后一个内容中负责确定运输地点的事情是什么。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document doc = null;
Document doc2 = null;
String a = "E:\1.xml" ;
String  c ;
try {
    db = dbf.newDocumentBuilder();
    doc = db.parse(new File(a));
    doc2 = db.parse(new File("E:\L (1).xml"));
    NodeList ndListFirstFile = doc.getElementsByTagName("med");
    Node nodeArea = doc.importNode(doc2.getElementsByTagName("end").item(0), true);
    NodeList nList2 = doc2.getElementsByTagName("end");
    for (int i = f; i <g; i++) {
        c = +i+"" ;
        doc2 = db.parse(new File("E:\L ("+c+").xml"));
        for (int temp = 0; temp < nList2.getLength(); temp++) {
            nodeArea = doc.importNode(doc2.getElementsByTagName("end").item(temp), true);
             ndListFirstFile.item(0).appendChild(nodeArea);
        }  
    } 

这是从两个文件中完成的,效果很好,但是转移标签的地方在内容的末尾。我要在内容开头

<med>
I move the Tag "dat" and it is moved at the end of the Tag "med" content
<dat>We have come to the wrong place, my friend</dat></med>

<med><dat>We want to get better here</dat>
I want to move Tag dat
To be the first content from Tag med
</med>

就是这样

来自 appendChild 文档:

Adds the node newChild to the end of the list of children of this node.

所以它按预期将其添加到末尾。

要在该节点上的任何其他元素之前插入它,您可以尝试:

ndListFirstFile.item(0).insertBefore(nodeArea, ndListFirstFile.item(0).getFirstChild());