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 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 String getChildText(Element parent, String childName) {
        Element child = getChildElement(parent, childName);

        if (child == null) {
            return null;
        }// w w  w  .  j  ava  2  s . c o  m

        return getText(child);
    }

    public static Element getChildElement(Element parent, String childName) {
        NodeList children = parent.getChildNodes();
        int size = children.getLength();

        for (int i = 0; i < size; i++) {
            Node node = children.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;

                if (childName.equals(element.getNodeName())) {
                    return element;
                }
            }
        }

        return null;
    }

    public static String getText(Element node) {
        StringBuffer sb = new StringBuffer();
        NodeList list = node.getChildNodes();

        for (int i = 0; i < list.getLength(); i++) {
            Node child = list.item(i);

            switch (child.getNodeType()) {
            case Node.CDATA_SECTION_NODE:
            case Node.TEXT_NODE:
                sb.append(child.getNodeValue());
            }
        }

        return sb.toString();
    }
}

Related

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