Here you can find the source of findElement(Node startNode, String name, String namespace)
name
and namespace
.
Parameter | Description |
---|---|
startNode | Where to start the search |
name | Local name of the element |
namespace | Namespace URI of the element |
null
public static Element findElement(Node startNode, String name, String namespace)
//package com.java2s; /**//from ww w .j a v a 2 s .c o m * 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 org.w3c.dom.Element; import org.w3c.dom.Node; public class Main { /** * Returns the first element that matches <code>name</code> and * <code>namespace</code>. <p/> This is a replacement for a XPath lookup * <code>//name</code> with the given namespace. It's somewhat faster than * XPath, and we do not deal with prefixes, just with the real namespace URI * * @param startNode Where to start the search * @param name Local name of the element * @param namespace Namespace URI of the element * @return The found element or <code>null</code> */ public static Element findElement(Node startNode, String name, String namespace) { // // Replace the formerly recursive implementation with a depth-first-loop // lookup // if (startNode == null) { return null; } Node startParent = startNode.getParentNode(); Node processedNode = null; while (startNode != null) { // start node processing at this point if (startNode.getNodeType() == Node.ELEMENT_NODE && startNode.getLocalName().equals(name)) { String ns = startNode.getNamespaceURI(); if (ns != null && ns.equals(namespace)) { return (Element) startNode; } if ((namespace == null || namespace.length() == 0) && (ns == null || ns.length() == 0)) { return (Element) startNode; } } processedNode = startNode; startNode = startNode.getFirstChild(); // no child, this node is done. if (startNode == null) { // close node processing, get sibling startNode = processedNode.getNextSibling(); } // no more siblings, get parent, all children // of parent are processed. while (startNode == null) { processedNode = processedNode.getParentNode(); if (processedNode == startParent) { return null; } // close parent node processing (processed node now) startNode = processedNode.getNextSibling(); } } return null; } }