Gets the XML element node with the given name - Java XML

Java examples for XML:XML Node

Description

Gets the XML element node with the given name

Demo Code

/*/*from  www  .  ja v a  2  s  . c o  m*/
 * EasyCukes is just a framework aiming at making Cucumber even easier than what it already is.
 * Copyright (C) 2014 Worldline or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main{
    /**
     * Gets the element node with the given name
     * 
     * @param doc
     *            a DOM Document object representing the XML content
     * @param name
     *            the name of the node to return
     * @return the node element
     * @throws Exception
     */
    private static Node getNode(Document doc, String name) throws Exception {
        NodeList list = doc.getDocumentElement().getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            // get the node having name element
            if (node.getNodeType() == Node.ELEMENT_NODE
                    && name.equals(node.getNodeName())) {
                Node data = node.getChildNodes().item(0);
                if (data.getNodeType() == Node.TEXT_NODE) {
                    return data;
                }
            }
        }
        return null;
    }
}

Related Tutorials