Java tutorial
//package com.java2s; /* * Copyright 2006-2010 the original author or authors. * * 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 org.w3c.dom.*; import java.util.*; public class Main { /** * Searches for a node within a DOM document with a given node path expression. * Elements are separated by '.' characters. * Example: Foo.Bar.Poo * @param doc DOM Document to search for a node. * @param pathExpression dot separated path expression * @return Node element found in the DOM document. */ public static Node findNodeByName(Document doc, String pathExpression) { final StringTokenizer tok = new StringTokenizer(pathExpression, "."); final int numToks = tok.countTokens(); NodeList elements; if (numToks == 1) { elements = doc.getElementsByTagNameNS("*", pathExpression); return elements.item(0); } String element = pathExpression.substring(pathExpression.lastIndexOf('.') + 1); elements = doc.getElementsByTagNameNS("*", element); String attributeName = null; if (elements.getLength() == 0) { //No element found, but maybe we are searching for an attribute attributeName = element; //cut off attributeName and set element to next token and continue Node found = findNodeByName(doc, pathExpression.substring(0, pathExpression.length() - attributeName.length() - 1)); if (found != null) { return found.getAttributes().getNamedItem(attributeName); } else { return null; } } StringBuffer pathName; Node parent; for (int j = 0; j < elements.getLength(); j++) { int cnt = numToks - 1; pathName = new StringBuffer(element); parent = elements.item(j).getParentNode(); do { if (parent != null) { pathName.insert(0, '.'); pathName.insert(0, parent.getLocalName());//getNodeName()); parent = parent.getParentNode(); } } while (parent != null && --cnt > 0); if (pathName.toString().equals(pathExpression)) { return elements.item(j); } } return null; } }