0

I am having some problem in deleting and copying the same xml element. The problem is I have 2 xml files and after comparing both I want to delete the element(s) those are only in file1 and at the same copy I want to copy these elements in a newly generated xml. I can delete the elements but I am not able to copy them in another xml file.

Here is the code:

for (Map.Entry<String, Element> entry : Map1.entrySet()) {
    String key = entry.getKey();

    if (!Map2.containsKey(key)) {
        Map1.remove(key);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document doc= builder.newDocument();
        Element rootElement =
            doc.createElementNS("", "missing");
        doc.appendChild(rootElement);
        //here i want to copy the deleted element in new xml file.      
        //rootElement.appendChild(Map1.get(key));
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);
        StreamResult newXml = new StreamResult(new File("C:/user/desktop/Output.xml"));
        transformer.transform(source, newXml);
    }
}
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
billu
  • 1
  • 2
  • If you can post a sample of your XML, I will submit a code sample that is the most efficient/kewlest, far better than the unwieldy dom code you have posted... – vtd-xml-author May 24 '16 at 19:41

1 Answers1

0

Shift the part where Map1.remove(key); to the end of the code. Your rootElement.appendChild(Map1.get(key)) would not work because key is no longer in Map1 after you removed it.

kanghj91
  • 140
  • 1
  • 9
  • i changed it as u said "kanghj" but it did not work. I am still getting the error ------ org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it. – billu Apr 28 '16 at 17:24
  • Right, next you will have to change `appendChild` to use `importNode` before it instead. Have a look at http://stackoverflow.com/questions/3184268/org-w3c-dom-domexception-wrong-document-err-a-node-is-used-in-a-different-docu – kanghj91 Apr 29 '16 at 06:49