Java XML Child Element Text getChildText(Element tag, String childTagName)

Here you can find the source of getChildText(Element tag, String childTagName)

Description

get Child Text

License

Open Source License

Declaration

public static String getChildText(Element tag, String childTagName) 

Method Source Code

//package com.java2s;
// are made available under the terms of the Eclipse Public License v1.0

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    public static String getChildText(Element tag, String childTagName) {
        Element child = getFirstChild(tag, childTagName);
        if (child != null) {
            return getNodeText(child);
        }// w  w w.  jav a2  s  .c o  m

        return ""; //$NON-NLS-1$
    }

    public static Element getFirstChild(Element tag, String childTagName) {
        NodeList nodes = tag.getElementsByTagName(childTagName);
        if (nodes == null || nodes.getLength() == 0) {
            return null;
        }

        return (Element) nodes.item(0);
    }

    /**
     * text of a leaf node, without child element
     * 
     * @param tag
     * @return String
     */
    public static String getNodeText(Element tag) {
        String text = tag.toString();
        int i = text.indexOf(">"); //$NON-NLS-1$
        int j = text.lastIndexOf("</"); //$NON-NLS-1$
        if (i < 0 || j < 0 || j < i) {
            return ""; //$NON-NLS-1$
        }

        return text.substring(i + 1, j);
    }
}

Related

  1. getChildText(Element parent, String childName)
  2. getChildText(Element parent, String childName)
  3. getChildText(Element parent, String kidName)
  4. getChildText(Element parent, String name)
  5. getChildText(Element root, String childName)
  6. getChildText(final Element element, final String tagName)
  7. getChildText(final Element element, final String tagName)
  8. getChildText(final Element parentElem, final String childName)
  9. getChildText(final Node node)