Java tutorial
//package com.java2s; /** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Helper Method. Searches through the child nodes of an element and returns an array of the matching nodes. * @param element Element * @param name String * @param caseSensitive boolean * @return ArrayList */ public static List<Node> getChildNodesByName(Node element, String name, boolean caseSensitive) { ArrayList<Node> nodes = new ArrayList<Node>(); NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (caseSensitive) { if (node.getNodeName().equals(name)) nodes.add(node); } else { if (node.getNodeName().equalsIgnoreCase(name)) nodes.add(node); } } return nodes; } /** * Returns the child nodes of the passed node where the type of the child node is in the passed array of type codes * @param node The node to return the child nodes of * @param types The short codes for the node types * @return a [possibly empty] list of nodes */ public static List<Node> getChildNodes(final Node node, short... types) { if (node == null) return Collections.emptyList(); if (types == null || types.length == 0) return Collections.emptyList(); final List<Node> nodes = new ArrayList<Node>(); for (Node n : nodeListToList(node.getChildNodes())) { if (Arrays.binarySearch(types, n.getNodeType()) >= 0) { nodes.add(n); } } return nodes; } /** * Returns the node in the passed node list as a list of nodes * @param nodeList The node list to render * @return a [possibly empty] list of nodes */ public static List<Node> nodeListToList(final NodeList nodeList) { if (nodeList == null) return Collections.emptyList(); final int size = nodeList.getLength(); if (size == 0) return Collections.emptyList(); final List<Node> nodes = new ArrayList<Node>(size); for (int i = 0; i < size; i++) { nodes.add(nodeList.item(i)); } return nodes; } }