A method to get value from the XML child node by providing child's node name - Java XML

Java examples for XML:XML Element Child

Description

A method to get value from the XML child node by providing child's node name

Demo Code


import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import java.io.UnsupportedEncodingException;

public class Main{
    /**//from w  w  w.j a va 2 s .  c  o m
     * A method to get value from the child node by providing child's node name
     * @param Node parent, a node to search the child nodes 
     * @param String nodeName, name of the child node to get
     * @return String , value of provided child node name
     */
    static public String getChildValue(Node parent, String nodeName) {
        String ret = "";

        Node n = parent.getFirstChild();
        while (n != null) {
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getNodeName().trim().equals(nodeName)) {
                    ret = XmlUtil.getNodeValue(n);
                }
            }
            n = n.getNextSibling();
        }
        return (ret);
    }
    /**
     * A method to get the value of desire node from xml document
     * @param Node parent, xml's node object to get
     * @return String , value from provided node
     */
    static public String getNodeValue(Node parent) {
        String ret = "";

        Node n = parent.getFirstChild();
        while (n != null) {
            if (n.getNodeType() == Node.TEXT_NODE) {
                try {
                    ret = n.getNodeValue().trim();
                } catch (NullPointerException ex) {
                    ret = "";
                    break;
                }
            }
            n = n.getNextSibling();
        }
        return (ret);
    }
}

Related Tutorials