Merging xml file using java NodeList

后端 未结 3 1194
悲&欢浪女
悲&欢浪女 2020-12-06 12:20

I\'m trying to merge two xml files as shown below but i can\'t able to get the desired output please help me thank you

Java code:

DocumentBuilderFac         


        
3条回答
  •  不思量自难忘°
    2020-12-06 13:08

    Problem is, you want to append child elements to "staff" element but what you actually do is :

    nodes.item(i).getParentNode().appendChild(n);
    

    meaning you're looking for the parent node of one of the "staff" nodes of the list, and that node is "company". So you're appending a new "staff" node (the one imported from doc1) to the "company" node of doc

    Now, what you want to do is to iterate over "staff" child nodes of doc1 and to append them one by one to the "staff" node of doc. So you would want to change nodes1 definition as following :

    // Retrieving child nodes of first "staff" element of doc1
    NodeList nodes1 = doc1.getElementsByTagName("staff").item(0).getChildNodes();
    

    Then change the node you append that to by replacing

    nodes.item(i).getParentNode().appendChild(n);
    

    by

    nodes.item(0).appendChild(n);
    

    So now you'll be appending all "staff" child nodes (/!\ only for the first "staff" element) of doc1 to the first "staff" element of doc

    Note 1 : Dont use the iteration variable (i) you use to run through list A to select an item of another list unless you're aware of what you're doing (for example both lists are of the same length)

    Note 2 : That solution will append the nodes of first "staff" element of doc1 to the first "staff" element of doc. You will maybe want to add some iterations here and there.

提交回复
热议问题