Java XML Element Text getElementTextByTagName(Element n, String elementName)

Here you can find the source of getElementTextByTagName(Element n, String elementName)

Description

get Element Text By Tag Name

License

Apache License

Declaration

public static String getElementTextByTagName(Element n, String elementName) 

Method Source Code

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

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

public class Main {
    public static String getElementTextByTagName(Element n, String elementName) {
        Element subEl = getElementByTagName(n, elementName);
        if (subEl != null)
            return getElementText(subEl);
        return null;
    }//  w w w .  java2 s.com

    /**
     * Gets the first child Element with a given name
     * 
     * @param n
     *            the node get the children from
     * @param elementName
     *            the name of the child elements
     * @return the first child Element with a given name
     */
    public static Element getElementByTagName(Element n, String elementName) {
        NodeList subNodes = n.getElementsByTagName(elementName);
        int sz = subNodes.getLength();
        if (sz > 0)
            return (Element) subNodes.item(0);
        return null;
    }

    public static String getElementText(Element n) {
        NodeList childNodes = n.getChildNodes();
        String result = new String();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (node.getNodeType() == Node.TEXT_NODE) {
                result += node.getNodeValue();
            }
        }
        return result;
    }
}

Related

  1. getElementText(Element elm)
  2. getElementText(Element n)
  3. getElementText(Element namedElement)
  4. getElementText(Element root, String tagname)
  5. getElementText(final Element element)
  6. getElementTextDataNoEx(Element element, boolean unindent)
  7. getElementTextOrNull(final XMLStreamReader reader)
  8. getElementTextValue(Element element)
  9. getElementTextValue(Element in)