get XML Children Values - Java XML

Java examples for XML:XML Element Child

Description

get XML Children 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<Vector<String>> getChildrenValues(
            Document document, String parentTag, String... childTags) {
        NodeList nodeList = document.getElementsByTagName(parentTag);
        Vector<Vector<String>> data = new Vector<Vector<String>>();

        for (int i = 0; i < nodeList.getLength(); ++i) {
            data.add(getChildValues(document, parentTag, i, childTags));
        }/*from www  .  jav  a  2s .c  om*/

        return data;
    }

    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));
            }
        }

        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