protected final Element findChildElement ( XmlModelWriter xw , Element parent , String childName , String keyAttributeName , String keyAttributeValue , boolean createIfNotPresent , String [ ] createOrder ) { NodeList childNodes = parent . getChildNodes ( ) ; for ( int i = 0 ; i < childNodes . getLength ( ) ; ++ i ) { Node node = childNodes . item ( i ) ; if ( node instanceof Element ) { Element childElement = ( Element ) node ; if ( childName . equals ( childElement . getTagName ( ) ) ) { // If there's no target key attribute to match, just return the element. if ( keyAttributeName == null ) { return childElement ; } // Return the element if the key attribute values match (or if both are null). String childElementAttributeValue = getElementAttribute ( childElement , keyAttributeName ) ; if ( ( keyAttributeValue == null && childElementAttributeValue == null ) || ( keyAttributeValue != null && keyAttributeValue . equals ( childElementAttributeValue ) ) ) { return childElement ; } } } } if ( createIfNotPresent ) { Element newChild = xw . getDocument ( ) . createElement ( childName ) ; Node insertBefore = null ; if ( createOrder != null ) { for ( int i = 0 ; i < createOrder . length ; i ++ ) { String nodeName = createOrder [ i ] ; if ( nodeName . equals ( childName ) ) { while ( ++ i < createOrder . length ) { insertBefore = findChildElement ( xw , parent , createOrder [ i ] , false , null ) ; if ( insertBefore != null ) { break ; } } break ; } } } if ( insertBefore != null ) { parent . insertBefore ( newChild , insertBefore ) ; } else { parent . appendChild ( newChild ) ; } if ( keyAttributeName != null && keyAttributeValue != null ) { newChild . setAttribute ( keyAttributeName , keyAttributeValue ) ; } return newChild ; } return null ; }
Find a child element by name and optionally add it if it isn t present .