Java XML Child Element Text getChildElementValueByTagName(Element parentElement, String childTag)

Here you can find the source of getChildElementValueByTagName(Element parentElement, String childTag)

Description

get Child Element Value By Tag Name

License

LGPL

Declaration

public static String getChildElementValueByTagName(Element parentElement, String childTag) 

Method Source Code

//package com.java2s;
/*//from  w  ww .j  av  a  2s  .co m
 * JFox - The most lightweight Java EE Application Server!
 * more details please visit http://www.huihoo.org/jfox or http://www.jfox.org.cn.
 *
 * JFox is licenced and re-distributable under GNU LGPL.
 */

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

import org.w3c.dom.Text;

public class Main {
    public static String getChildElementValueByTagName(Element parentElement, String childTag) {
        if (childTag.equals(parentElement.getNodeName())) {
            return getNodeValue(parentElement);
        }
        for (Node temp = parentElement.getFirstChild(); temp != null; temp = temp.getNextSibling()) {
            if (temp.getNodeType() == Node.ELEMENT_NODE && childTag.equals(temp.getNodeName())) {
                return getNodeValue(temp);
            }
        }
        return null;
    }

    public static String getNodeValue(Node node) {
        if (node == null) {
            return null;
        } else if (node instanceof Text) {
            return node.getNodeValue().trim();
        } else if (node instanceof Element) {
            node.normalize();
            Node temp = node.getFirstChild();
            if (temp != null && (temp instanceof Text))
                return temp.getNodeValue().trim();
            else
                return "";
        } else {
            return node.getNodeValue().trim();
        }
    }
}

Related

  1. getChildElementValue(Element p_rootElement, String p_elementName)
  2. getChildElementValue(Element parent, String name)
  3. getChildElementValue(Element parentElm, String elementName, String defaultValue)
  4. getChildElementValueByTagName(Element ele, String childEleName)
  5. getChildElementValueByTagName(Element ele, String childEleName)
  6. getChildText(Element elem, String childTagName)
  7. getChildText(Element element, String defaultValue)
  8. getChildText(Element element, String nodeName)
  9. getChildText(Element element, String tag)