get XML Direct Child Node - Java XML

Java examples for XML:XML Node Child

Description

get XML Direct Child Node

Demo Code

/*****************************************************************************
 * Copyright (c) 2007 Jet Propulsion Laboratory,
 * California Institute of Technology.  All rights reserved
 *****************************************************************************/
//package com.java2s;
import java.util.LinkedList;
import java.util.List;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Node getDirectChildNode(Node node, String name) {
        Node targetNode = null;/*  w  ww. j a v a  2 s  .  c  o  m*/

        List<Node> nodes = getDirectChildNodes(node, name);
        if (nodes.size() == 1) {
            targetNode = nodes.get(0);
        }

        return targetNode;
    }

    public static List<Node> getDirectChildNodes(Node node, String name) {
        LinkedList<Node> nodes = new LinkedList<Node>();

        NodeList childList = node.getChildNodes();
        for (int childIndex = 0; childIndex < childList.getLength(); childIndex++) {
            Node child = childList.item(childIndex);
            if (child.getNodeName().equals(name)) {
                nodes.add(child);
            }
        }

        return nodes;
    }
}

Related Tutorials