Skip to main content

Effective XML processing with DOM and XPath in Java

Analysis of many projects yields advice and suggested code


  public static String getTextContents ( Node node )
  {
    NodeList childNodes;
    StringBuffer contents = new StringBuffer();
    
    childNodes =  node.getChildNodes();
    for(int i=0; i < childNodes.getLength(); i++ )
    {
      if( childNodes.item(i).getNodeType() == Node.TEXT_NODE )
      {
	contents.append(childNodes.item(i).getNodeValue());
      }
    }
    return contents.toString();
  } 

  public static String findValue(Node node, String xql) throws Exception
  {

    if( (xql == null) || (xql.length() == 0) ) {
      throw new Exception("findValue called with empty xql statement");
    }

    if(node == null) {
      throw new Exception("findValue called with null node");
    }
    return getTextContents( XPathAPI.selectSingleNode(node,xql) );
  } 


Return to article