Java tutorial
//package com.java2s; // Licensed under the Apache License, Version 2.0 (the "License"); import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Get text data of first XML {@code org.w3c.dom.Element} of given name. * * @param elem the parent XML Element * @param name the name of the child text Element * @return text data of named child Element */ public static String getFirstElementByTagName(Element elem, String name) { return getElementByTagName(elem, name, null); } /** * Get text data of first XML {@code org.w3c.dom.Element} of given name. * * @param elem the parent XML Element * @param name the name of the child text Element * @param emptyValue value to return if element exists, but is empty * @return text data of named child Element */ private static String getElementByTagName(Element elem, String name, String emptyValue) { NodeList nodeList = elem.getElementsByTagName(name); if (nodeList.getLength() == 0) { return null; } NodeList children = nodeList.item(0).getChildNodes(); if (children.getLength() == 0 || children.item(0).getNodeType() != Node.TEXT_NODE) { return emptyValue; } return children.item(0).getNodeValue(); } }