Java XML Child Element Text getChildTextByName(Element parent, String name)

Here you can find the source of getChildTextByName(Element parent, String name)

Description

Equivalent to getTextContent(getFirstChildByName(e, n)), with a null check.

License

Apache License

Parameter

Parameter Description
parent parent element
name child element name

Declaration

public static String getChildTextByName(Element parent, String name) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.*;

public class Main {
    /**/* w ww  . java 2 s  . c om*/
     * 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

  1. getChildText(Node node)
  2. getChildText(Node node)
  3. getChildText(Node parent, String childName)
  4. getChildTextAsBoolean(Element parent, String childName, boolean defValue)
  5. getChildTextAsBooleanObj(Element parent, String childName, Boolean defValue)
  6. getChildTextByTagName(Element e, String tagName)
  7. getChildTextContent(Element elemenet, String childElemenetName)
  8. getChildTextContent(Element element, String childTagName)
  9. getChildTextList(Element elem, String childTagName)