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 { /** * Returns the child element nodes of the passed node * @param node The node to return the element child nodes of * @return a [possibly empty] list of nodes */ public static List<Node> getElementChildNodes(final Node node) { return getChildNodes(node, Node.ELEMENT_NODE); } /** * 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; } }