Attempts to list all of the nodes of type Element from the list with the provided tag name - Java XML

Java examples for XML:XML Node Operation

Description

Attempts to list all of the nodes of type Element from the list with the provided tag name

Demo Code


//package com.java2s;
import java.util.ArrayList;

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

public class Main {
    /**//from ww w  .  j  a  v a2 s . c o m
     * Attempts to list all of the nodes of type Element from the list with the
     * provided tag name using the
     * {@link DOMHelper#isNodeOfType(Node, String, boolean)} checker.
     *
     * @param list
     *            The NodeList object.
     * @param tagName
     *            The tag name.
     * @param caseSensitive
     *            If the match should be treated as case-sensitive.
     * @return A list of all Node objects which are an Element and have a tag
     *         name of that provided, or an empty array if no such item exists.
     */
    public static Node[] findNodesOf(NodeList list, String tagName,
            boolean caseSensitive) {
        ArrayList<Node> result = new ArrayList<Node>();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (isNodeOfType(node, tagName, caseSensitive))
                result.add(node);
        }
        return result.toArray(new Node[0]);
    }

    /**
     * Attempts to match the provided node to the Element type with the tag name
     * provided.
     *
     * @param node
     *            The node object.
     * @param tagName
     *            The tag name.
     * @param caseSensitive
     *            If the match should be treated as case-sensitive.
     * @return If the Node object is an Element and has a tag name of that
     *         provided.
     */
    public static boolean isNodeOfType(Node node, String tagName,
            boolean caseSensitive) {
        if (!(node instanceof Element))
            return false;
        Element nodeAsElement = (Element) node;
        if (caseSensitive && nodeAsElement.getTagName().equals(tagName))
            return true;
        if (!caseSensitive
                && nodeAsElement.getTagName().equalsIgnoreCase(tagName))
            return true;
        return false;
    }
}

Related Tutorials