code: private Element replaceOrAddElement(Document doc, Element parent, String name, List<String> beforeNames) {
          NodeList children = parent.getChildNodes();
          List<Element> elements = new LinkedList<Element>();
          for (int cn = 0; cn < children.getLength(); cn++) {
              if (children.item(cn) instanceof Element && children.item(cn).getNodeName().equals(name)) {
                  elements.add((Element) children.item(cn));
              }
          }
          Element element;
          if (elements.isEmpty()) {
              Element newElement = doc.createElement(name);
              Node first = null;
              for (String n: beforeNames) {
                  first = findChild(parent, n);
                  if (first != null) {
                      break;
                  }
              }
  
              Node node;
              if (first != null) {
                  node = first;
              } else {
                  node = parent.getFirstChild();
              }
              Text text = doc.createTextNode("\n" + indent);
              parent.insertBefore(text, node);
              parent.insertBefore(newElement, text);
              element = newElement;
          } else {
              element = elements.get(0);
          }
  
          return element;
      }
docs: Returns new or existing Element from <code>parent</code>