get XML Child Element As String - Java XML

Java examples for XML:XML Element Child

Description

get XML Child Element As String

Demo Code


//package com.java2s;

import org.w3c.dom.Element;

public class Main {
    public static String getChildAsString(Element parent, String childName) {
        if (doesElementContainChildren(parent, childName)) {
            return getFirstChildElement(parent, childName).getTextContent();
        }//w w  w. ja va  2s  . co  m
        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;
    }

    public static Element getFirstChildElement(Element parent,
            String childName) {
        if (parent.getElementsByTagName(childName).getLength() > 0) {
            return (Element) parent.getElementsByTagName(childName).item(0);
        }
        return null;
    }
}

Related Tutorials