question: public static void addNewNode ( final Document doc , final XmlEntity xmlEntity ) throws IOException , XPathExpressionException , SAXException , ParserConfigurationException { final LinkedHashMap < String , CacheElement > elementOrderMap = CacheElement . buildElementMap ( doc ) ; final Node newNode = createNode ( doc , xmlEntity . getXmlDefinition ( ) ) ; final Node root = doc . getDocumentElement ( ) ; final int incomingElementOrder = getElementOrder ( elementOrderMap , xmlEntity . getNamespace ( ) , xmlEntity . getType ( ) ) ; boolean nodeAdded = false ; NodeList nodes = root . getChildNodes ( ) ; final int length = nodes . getLength ( ) ; for ( int i = 0 ; i < length ; i ++ ) { final Node node = nodes . item ( i ) ; if ( node instanceof Element ) { final Element childElement = ( Element ) node ; final String type = childElement . getLocalName ( ) ; final String namespace = childElement . getNamespaceURI ( ) ; if ( namespace . equals ( xmlEntity . getNamespace ( ) ) && type . equals ( xmlEntity . getType ( ) ) ) { String nameOrId = getAttribute ( childElement , "name" ) ; if ( nameOrId == null ) { nameOrId = getAttribute ( childElement , "id" ) ; } if ( nameOrId != null ) { if ( nameOrId . equals ( xmlEntity . getNameOrId ( ) ) ) { root . replaceChild ( newNode , node ) ; nodeAdded = true ; break ; } } else { if ( ! isMultiple ( elementOrderMap , namespace , type ) ) { root . replaceChild ( newNode , node ) ; nodeAdded = true ; break ; } } } else { if ( incomingElementOrder < getElementOrder ( elementOrderMap , namespace , type ) ) { root . insertBefore ( newNode , node ) ; nodeAdded = true ; break ; } } } } if ( ! nodeAdded ) { root . appendChild ( newNode ) ; } }
target:  Adds a new node or replaces an existing node in the Document