Let's consider the following XML document:
<items>
   <item>item1</item>
   <item>item2</item>
</items>
Now, let's remove all the items and add some new item. Code:
  //-- assume we have Element instance of <items> element: items_parent
  //   and the Document instance: doc
  //-- remove all the items
  NodeList items = items_parent.getElementsByTagName("item");
  for (int i = 0; i < items.getLength(); i++){
     Element curElement = (Element)items.item(i);
     items_parent.removeChild(curElement);
  }
  //-- add a new one
  Element new_item = doc.createElement("item");
  new_item.setTextContent("item3");
  items_parent.appendChild(new_item);
New contents of the file:
<items>
   <item>item3</item>
</items>
These annoying blank lines appeared because removeChild() removes child, but it leaves indent of removed child, and line break too. And this indent_and_like_break is treated as a text content, which is left in the document.
In the related question I posted workaround:
items_parent.setTextContent("");
It removes these blank lines. But this is some kink of hack, it removes the effect, not the cause.
So, the question is about removing the cause: how to remove child with its intent with line break?