get XML Element Text Node Value - Android XML

Android examples for XML:XML Node

Description

get XML Element Text Node Value

Demo Code

/*L/*from  www.  ja  va  2  s.c  o m*/
 *  Copyright SAIC, Ellumen and RSNA (CTP)
 *
 *
 *  Distributed under the OSI-approved BSD 3-Clause License.
 *  See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details.
 */
//package com.java2s;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static String getElementTextNodeValue(Node root,
            String nodeString) {
        Element elem = getElementNode(root, nodeString);
        if (elem == null) {
            return null;
        }
        NodeList nlist = elem.getChildNodes();

        if (nlist == null) {
            return null;
        }
        for (int i = 0; i < nlist.getLength(); i++) {
            if (nlist.item(i).getNodeType() == Node.TEXT_NODE) {
                return nlist.item(i).getNodeValue();
            }
        }

        return null;
    }

    public static Element getElementNode(Node root, String nodeString) {
        NodeList nlist = root.getChildNodes();

        for (int i = 0; i < nlist.getLength(); i++) {
            if (nlist.item(i) instanceof Element) {
                if (nlist.item(i).getNodeName()
                        .equalsIgnoreCase(nodeString)) {
                    return (Element) nlist.item(i);
                }

                if (nlist.item(i).hasChildNodes()) {
                    Element retNode = getElementNode(nlist.item(i),
                            nodeString);

                    if (retNode != null) {
                        return retNode;
                    }
                }
            }
        }

        return null;
    }
}

Related Tutorials