title: How to add sibling and child nodes into a XML file?
body: <p>The purpose of my program is to add a group of words that are in an array within a loop. Assume in each iteration it should add words from a starting index to an ending index to a node as its children. The XML file and each node should be made in a run-time basis, but there is a consideration that if the program is stopped and then run the program again, it should continue adding new words into the existing XML file by adding a new node after the last existing node. Here is how I get to make the XML file and add nodes to it, but it adds nodes to the root node and they are without any child (the child should be added into each node within an iteration but they are considered as a separate node and not a child node):</p>
  
  <pre><code>    private static void createXML(String word, int id) {
  
          Element Word= doc.createElement("word"+id);
          rootElement.appendChild(Word);
                  //doc.appendChild(Word);
  
          Attr attr = doc.createAttribute("id");
          attr.setValue(Integer.toString(id));
          Word.setAttributeNode(attr);
  
          Element Content= doc.createElement("content");
          Content.appendChild(doc.createTextNode(word));
          Word.appendChild(Content);
  
      }
  
  
  
       private static void saveXML() {
       transformerFactory = TransformerFactory.newInstance();
       transformer = transformerFactory.newTransformer();
       DOMSource source = new DOMSource(doc);
       StreamResult result = new StreamResult(new File("g:\\words.xml"));
       transformer.transform(source, result);   
  
  }
  
   public static void main(String[] args){
  
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      Element doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("WORDS");
      doc.appendChild(rootElement);
  
              for(int i=m, i&lt;n; i++)
              createXML(array[m...n], i);
  
              saveXML();
  
                  }
  </code></pre>