code: public static void addRelativeTo(Element parent, Element child, String tagname, boolean first) {
      NodeList nodes = parent.getChildNodes();
      if(nodes.getLength() > 0) {
        Node relativeEl = null;
        boolean found = false;
        for(int i=0; i < nodes.getLength(); i++) {
          Node node = nodes.item(i);
          if(node.getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) node;
            if(el.getTagName().equals(tagname)) {
              if(relativeEl == null || !first) {
                relativeEl = el;
              } else if(first && !found) {
                relativeEl = el;
              }
              found = true;
            }
          }
        }
        if(relativeEl != null && !first) {
          relativeEl = relativeEl.getNextSibling();
        }
        if(relativeEl == null && first) {
          relativeEl = nodes.item(0);
        } else {
          parent.appendChild(child);
        }
        if(relativeEl != null) {
          parent.insertBefore(child, relativeEl);
        }
      } else {
        //There are no elements in the parent node so lets just append child.
        parent.appendChild(child);
      }
    }
docs: <p>Adds a child xml element to a parent element relative to other elements with a tagname.</p>
  <p>If first is true then the child is added before any elements with a tagname, the opposite happens when first is false.</p>
  @param parent The parent xml element.
  @param child The child xml element to add.
  @param tagname The tagname to be relative to.
  @param first A flag that describes the relative relationship between the child element and its siblings named by tagname.