Java XML Element Get by Name getElementValue(Element parent, String tagName)

Here you can find the source of getElementValue(Element parent, String tagName)

Description

get Element Value

License

Apache License

Declaration

public static String getElementValue(Element parent, String tagName) 

Method Source Code

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

import java.util.ArrayList;
import java.util.List;

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

public class Main {
    public static String getElementValue(Element parent, String tagName) {
        Element element = getChildElement(parent, tagName);
        if (element != null) {
            NodeList nodes = element.getChildNodes();
            if ((nodes != null) && (nodes.getLength() > 0)) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    if ((node instanceof Text)) {
                        return ((Text) node).getData();
                    }/*  w w  w  .  j  a va2 s . com*/
                }
            }
        }
        return null;
    }

    public static String getElementValue(Element element) {
        if (element != null) {
            NodeList nodes = element.getChildNodes();
            if ((nodes != null) && (nodes.getLength() > 0)) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    if ((node instanceof Text)) {
                        return ((Text) node).getData();
                    }
                }
            }
        }
        return null;
    }

    public static Element getChildElement(Element parent, String tagName) {
        List<Element> children = getChildElements(parent, tagName);
        if (children.isEmpty()) {
            return null;
        }
        return (Element) children.get(0);
    }

    public static List<Element> getChildElements(Element parent, String tagName) {
        NodeList nodes = parent.getElementsByTagName(tagName);
        List<Element> elements = new ArrayList();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (((node instanceof Element)) && (node.getParentNode() == parent)) {
                elements.add((Element) node);
            }
        }
        return elements;
    }
}

Related

  1. getElementsByTagName(Element parent, String tagName)
  2. getElementsByTagName(final Element parentElement, final String elementName)
  3. getElementsByTagNameCaseInsensitive( Document doc, final Set lowerCaseNames)
  4. getElementValue(Element parent)
  5. getElementValue(Element parent, String tagName)
  6. getFirstElement(Element parent, String name)
  7. getFirstElementAtAnyDepthByNodeName(Element parent, String name)
  8. getFirstElementByName(Element parent, String name)
  9. getFirstElementByName(String name, Element parent)