is Direct XML Child Node Defined - Java XML

Java examples for XML:XML Node Child

Description

is Direct XML Child Node Defined

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 boolean isDirectChildNodeDefined(Node node, String name) {
        Node targetNode = getDirectChildNode(node, name);
        return (targetNode != null) ? true : false;
    }//from   w  w w  .j  a  v  a 2  s  .  c  o  m

    public static Node getDirectChildNode(Node node, String name) {
        Node targetNode = null;

        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