Skip to main content

Effective XML processing with DOM and XPath in Java

Analysis of many projects yields advice and suggested code

  public static Node setValue(Node startNode, String value, String xql)
    throws Exception
  {
    Node targetNode = XPathAPI.selectSingleNode( startNode,xql );

    NodeList children = targetNode.getChildNodes();
    int index = 0;
    int length = children.getLength();

    // Remove all of the current contents
    for(index = 0; index < length; index++) {
      targetNode.removeChild( children.item( index ) );
    }

    // Add in the new value
    Document doc = startNode.getOwnerDocument();
    targetNode.appendChild( doc.createTextNode(value) );
        
    return targetNode;
  }

Return to article