5 Replies Latest reply on Sep 8, 2011 6:25 PM by DrClap

    [DOM] How to insert a new node ?

      Hi guys, I am a bit novice to the subject of XML in Java.
      After some time I got to read the data from xml to my Java objects.
      Now I would like to make the opposite. Write an xml node from Java Object.

      This is my xml :

      +<?xml version="1.0" encoding="UTF-8"?>+


      I would like to add the whole part from <coin> to </coin>.

      Is it possible ? How to do it?
      Thanks in advance

        • 1. Re: [DOM] How to insert a new node ?
          To create a node which you are going to insert into a Document, you call one of the Document's methods whose names are like createElement, createTextNode, and so on.

          Then to put that node into the Document, you decide what its parent node is going to be, and call one of that node's methods whose names are like appendChild and insertBefore.
          • 2. Re: [DOM] How to insert a new node ?
            Previously I made something like this :

            Element element = (Element) dom.getElementsByTagName("coin").item(1);
            Element Nelement = dom.createElement("test");
            dom.insertBefore(Nelement, element);

            but I got errors :

            Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
            at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(CoreDocumentImpl.java:391)
            at monetownik.coinDatabase.addRecord(coinDatabase.java:34)
            at monetownik.monetownik.main(monetownik.java:26)
            Java Result: 1

            What shall I do ?
            • 3. Re: [DOM] How to insert a new node ?
              Don't insert the node where it isn't permitted, of course.

              That would require you to figure out where you were trying to insert the node and why it wasn't permitted to insert it there. We don't have any context to be able to figure that out.
              • 4. Re: [DOM] How to insert a new node ?
                Yes you have a context :)

                <?xml version="1.0" encoding="UTF-8"?>



                Element element = (Element) dom.getElementsByTagName("coin").item(1); // I look for the second <coin>...</coin>
                Element Nelement = dom.createElement("test"); // I create new element <test>
                dom.insertBefore(Nelement, element); // and then I put it one before another

                So why I have a message that is not permitted ?
                • 5. Re: [DOM] How to insert a new node ?
                  Read the documentation.
                  Inserts the node newChild before the existing child node refChild.
                  Here "newChild" is your "test" element and "refChild" is your "coin" element. Which is NOT a child of the document element. It's a child of the "Base" element.