title: Replacing XML node via Java
body: <p>I wan to replace a node in XML document with another and as a consequence replace all it's children with other content. Following code should work, but for an unknown reason it doesn't.</p>
  
  <pre><code>File xmlFile = new File("c:\\file.xml");
  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(xmlFile);
  doc.getDocumentElement().normalize();
  
  NodeList nodes = doc.getElementsByTagName("NodeToReplace");
  for (int i = 0; i &lt; nodes.getLength(); i++) {
  
      NodeList children = nodes.item(i).getChildNodes();
      for (int j = 0; j &lt; children.getLength(); j++) {
            nodes.item(i).removeChild(children.item(j));
      }
          doc.renameNode(nodes.item(i), null, "MyCustomTag");  
  }
  </code></pre>
  
  <p>EDIT-</p>
  
  <p>After debugging it for a while, I sovled it. The problem was in moving index of the children array elmts. Here's the code:</p>
  
  <pre><code>NodeList nodes = doc.getElementsByTagName("NodeToReplace");
  for (int i = 0; i &lt; nodes.getLength(); i++) {
  
      NodeList children = nodes.item(i).getChildNodes();
  
      int len = children.getLength();
      for (int j = len-1; j &gt;= 0; j--) {
          nodes.item(i).removeChild((Node) children.item(j));
      }
      doc.renameNode(nodes.item(i), null, "MyCustomTag");  
  }
  </code></pre>