get XML Child Values - Java XML

Java examples for XML:XML Element Child

Description

get XML Child Values

Demo Code


//package com.java2s;
import java.util.Vector;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Vector<String> getChildValues(Document document,
            String parentTag, int parentIndex, String... childTags) {
        NodeList nodeList = document.getElementsByTagName(parentTag);
        Node node = nodeList.item(parentIndex);
        Vector<String> data = new Vector<String>();

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) node;

            for (String s : childTags) {
                data.add(getTagValue(s, eElement));
            }/*from  w w  w.  j  a v a2s  .c om*/
        }

        return data;
    }

    public static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
                .getChildNodes();

        Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
    }
}

Related Tutorials