Java tutorial
//package com.java2s; /* Weave (Web-based Analysis and Visualization Environment) Copyright (C) 2008-2011 University of Massachusetts Lowell This file is a part of Weave. Weave is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, Version 3, as published by the Free Software Foundation. Weave is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Weave. If not, see <http://www.gnu.org/licenses/>. */ import java.util.List; import java.util.Vector; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * getStringListFromXPath * Gets a list of strings from an xml. * @param rootNodeExpression Evaluated on the root of the sqlconfig document to get a single Node. * @param listExpression Evaluated on the Node returned by rootNodeExpression, gets a NodeList. * @return A list of the text contents of the NodeList returned by evaluating the listExpression. */ public static List<String> getStringListFromXPath(Document doc, XPath xpath, String rootNodeExpression, String listExpression) { synchronized (xpath) { try { return getStringListFromXPath((Node) xpath.evaluate(rootNodeExpression, doc, XPathConstants.NODE), xpath, listExpression); } catch (Exception e) { System.err.println("Error evaluating xpath expression: " + rootNodeExpression); e.printStackTrace(); } return new Vector<String>(); } } /** * getStringListFromXPath * Gets a list of strings from an xml. * @param rootNode The root node to perform the listExpression on. * @param listExpression Evaluated on the rootNode, gets a NodeList. * @return A list of the text contents of the nodes returned by evaluating the listExpression. */ public static List<String> getStringListFromXPath(Node rootNode, XPath xpath, String listExpression) { synchronized (xpath) { if (rootNode instanceof Document) rootNode = ((Document) rootNode).getDocumentElement(); Vector<String> result = new Vector<String>(); try { NodeList nodes = (NodeList) xpath.evaluate(listExpression, rootNode, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { result.addElement(nodes.item(i).getTextContent()); } } catch (Exception e) { System.err.println("Error evaluating xpath expression: " + listExpression); e.printStackTrace(); } return result; } } }