Equivalent to getTextContent(getFirstChildByName(e, n)), with a null check for XML Element - Java XML

Java examples for XML:XML Element Child

Description

Equivalent to getTextContent(getFirstChildByName(e, n)), with a null check for XML Element

Demo Code


//package com.java2s;
import org.w3c.dom.*;

public class Main {
    /**/* w w  w . j  a  v  a2 s.  co m*/
     * Equivalent to getTextContent(getFirstChildByName(e, n)), with
     * a null check.
     * 
     * @param parent parent element
     * @param name child element name
     * @return
     */
    public static String getChildTextByName(Element parent, String name) {
        Element e = getFirstChildByName(parent, name);
        return (e != null) ? getTextContent(e) : null;
    }

    /**
     * Return the first child element with a given name.  
     * @param parent parent element
     * @param name child element name
     * @return 
     */
    public static Element getFirstChildByName(Element parent, String name) {
        NodeList children = parent.getElementsByTagName(name);
        if (children.getLength() == 0) {
            return null;
        }
        return (Element) children.item(0);
    }

    /**
     * Returns normalized text content for a node.
     * @param node
     * @return text content of child node, trimmed
     */
    public static String getTextContent(Node node) {
        return node.getTextContent().trim();
    }
}

Related Tutorials