Java tutorial
//package com.java2s; /* * Copyright (c) 2013, University of Toronto. * * Licensed 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.LinkedList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main { public static List<String> getAllLeaves(Element element) { // Get a list of strings representing the relative path // (including the current element) to all the leaf elements // under the current element // Eric: Why return a List? Returning a Set seems to make // more sense. if (element == null) { return null; } List<String> ret = new LinkedList<String>(); if (isLeaf(element)) { ret.add(element.getNodeName()); } else { NodeList nl = element.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n instanceof Element) { Element childElement = (Element) n; for (String childNodeName : getAllLeaves(childElement)) { ret.add(element.getNodeName() + "/" + childNodeName); } } } } return ret; } public static boolean isLeaf(Node node) { NodeList nodeList = node.getChildNodes(); boolean hasElement = false; for (int i = 0; i < nodeList.getLength(); i++) { Node child = nodeList.item(i); if (child instanceof Text) { if (!"".equals(child.getTextContent().trim())) { // The current node is a leaf node if it contains // at least one text node with non-empty text values return true; } } if (child instanceof Element) { hasElement = true; } } // The current node is also a leaf node if it // contains no elements at all return !hasElement; } }