get XML Children Element As Strings - Java XML

Java examples for XML:XML Element Child

Description

get XML Children Element As Strings

Demo Code


//package com.java2s;

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

public class Main {
    public static String[] getChildrenAsStrings(Element parent,
            String childName) {//from w  w  w .  j  ava2s . c o m
        if (doesElementContainChildren(parent, childName)) {
            NodeList children = parent.getElementsByTagName(childName);
            String[] strings = new String[children.getLength()];
            for (int i = 0; i < children.getLength(); i++) {
                strings[i] = children.item(i).getTextContent();
            }
            return strings;
        }
        return null;
    }

    public static boolean doesElementContainChildren(Element parent,
            String... childNames) {
        boolean missingChild = false;
        for (String childName : childNames) {
            if (parent.getElementsByTagName(childName).getLength() == 0) {
                missingChild = true;
            }
        }
        if (missingChild)
            return false;
        else
            return true;
    }
}

Related Tutorials