JavaRanch Home    
 
This page:         last edited 17 March 2007         What's Changed?         Edit

Get Node Value   

The org.w3c.dom package contains an interface 'Node', which has (among others) methods getNodeName() and getNodeValue(). Now, there is often some unclarity regarding what these methods actually return for different types of Nodes...

The best resource for resolving the answer is the official javadocs (http://java.sun.com/j2se/1.4.1/docs/api/index.html) for the Node interface. There's a table listing what the return value actually is for your particular Node type:

nodeTypenodeNamenodeValueattributes
Attrname of attributevalue of attributenull
CDATASection" "content of the CDATA Sectionnull
Comment" "content of the commentnull
Document" "nullnull
DocumentFragment?" "nullnull
DocumentType?document type namenullnull
Elementtag namenullNamedNodeMap?
Entityentity namenullnull
EntityReference?name of entity referencednullnull
Notationnotation namenullnull
ProcessingInstruction?targetentire content excluding the targetnull
Text" "content of the text nodenull

Notice that the getNodeValue() method for an instance of org.w3c.dom.Element, "<elem>value</elem>" for example, does not return the value of its contents. Instead, you need to getChildNodes() and concatenate the values of the Text nodes (there may be more than one) in order to get the enclosing Element's value.

The following is a sample snippet returning the value (contents) of an Element node:


    public static String getNodeValue(Node node) {
        StringBuffer buf = new StringBuffer();
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node textChild = children.item(i);
            if (textChild.getNodeType() != Node.TEXT_NODE) {
                System.err.println("Mixed content! Skipping child element " + textChild.getNodeName());
                continue;
            }
            buf.append(textChild.getNodeValue());
        }
        return buf.toString();
    }


XmlFaq CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2012 Paul Wheaton