Java XML Child Element Text getChildText(Element parent, String childName)

Here you can find the source of getChildText(Element parent, String childName)

Description

get Child Text

License

Open Source License

Declaration

public static final String getChildText(Element parent, String childName) 

Method Source Code

//package com.java2s;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static final String getChildText(Element parent, String childName) {
        Element childElement = getFirstLevelChildElementByTagName(parent, childName);

        if (childElement != null) {
            return getText(childElement);
        }//from w w w . java 2s . com

        return null;
    }

    public static final Element getFirstLevelChildElementByTagName(Element parent, String elementName) {
        Node childNode = parent.getFirstChild();
        while (childNode != null) {
            if ((childNode.getNodeType() == Node.ELEMENT_NODE)
                    && ((Element) childNode).getLocalName().equals(elementName)) {
                return (Element) childNode;
            }
            childNode = childNode.getNextSibling();
        }
        return null;
    }

    public static final String getText(Element elem) {
        if (elem != null) {
            NodeList childNodes = elem.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                if (childNodes.item(i).getNodeType() == Node.TEXT_NODE) {
                    return trim(childNodes.item(i).getNodeValue());
                }
            }
        }

        return null;
    }

    public static String trim(String input) {
        if (input == null) {
            return input;
        }

        return input.trim();

        // int len = input.length();
        //
        // int index = 0;
        //
        // for(index = 0;index < len;index++)
        // {
        // if(!Character.isWhitespace(input.charAt(index)))
        // {
        // break;
        // }
        // }
        //
        // return (index == 0) ? input : input.substring(index);
    }
}

Related

  1. getChildText(Element element, String defaultValue)
  2. getChildText(Element element, String nodeName)
  3. getChildText(Element element, String tag)
  4. getChildText(Element element, String tag)
  5. getChildText(Element parent, String childLocalName, String childNamespaceURI)
  6. getChildText(Element parent, String childName)
  7. getChildText(Element parent, String childName)
  8. getChildText(Element parent, String childName)
  9. getChildText(Element parent, String kidName)