Java Utililty Methods XML Child Node Get

List of utility methods to do XML Child Node Get

Description

The list of methods to do XML Child Node Get are organized into topic(s).

Method

StringgetChildNodeValue(Element root, String childNodeName, String defaultValue)
get Child Node Value
NodeList nl = root.getElementsByTagName(childNodeName);
if (nl.getLength() == 1) {
    return getTextValue(nl.item(0)).trim();
} else if (defaultValue == null) {
    throw new SAXException("Node <" + root.getNodeName() + "> has no child named <" + childNodeName + ">");
} else {
    return defaultValue;
StringgetChildNodeValue(Node node, String elementName)
get Child Node Value
return ((Element) node).getElementsByTagName(elementName).item(0).getTextContent();
StringgetChildNodeValue(Node root, String childName, boolean emptyStringOnMissingChild)
Instead of using XPathAPI.selectSingleNode(root, "name")); use getChildNodeValue(root, "name"); This is much quicker!
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
    if (nl.item(i).getNodeName().equals(childName)) {
        Node textNode = nl.item(i).getFirstChild();
        if (textNode == null)
            return "";
        else
            return textNode.getNodeValue();
...
StringgetChildNodeValue(String childNodeName, Node n)
searches for a child of n called childNodeName.
Node child = getChildNodeWithName(childNodeName, n);
return child.getNodeValue();
StringgetChildNodeValueByName(Node parent, String nodeName)
Gets a node value by name
Node node = findChildNodeByName(parent, nodeName);
if (node != null && node.getFirstChild() != null) {
    return node.getFirstChild().getNodeValue().trim();
return "";
NodegetChildNodeWithName(Node node, String name, String namespaceURI)
get Child Node With Name
List all = getChildNodesWithName(node, name, namespaceURI);
if (all.size() > 1) {
    throw new IllegalArgumentException("Expected only one node " + name + " for " + node);
if (all.size() > 0) {
    return (Node) all.get(0);
return null;
...
NodegetChildNodeWithName(String name, Node n)
looks through the child nodes of n and returns the first child with name
NodeList nl = n.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
    Node c = nl.item(i);
    if (c.getNodeName().equals(name)) {
        return c;
return null;
...
NodegetChildNodeWithTag(Node node, String nodeTag)
get Child Node With Tag
NodeList elements = node.getChildNodes();
if (elements != null) {
    Node childNode;
    for (int i = 0; i < elements.getLength(); i++) {
        childNode = elements.item(i);
        if (childNode.getNodeName().equals(nodeTag))
            return childNode;
return null;