Here you can find the source of getElement(Element root, String name)
Parameter | Description |
---|---|
root | The element to search. |
name | The local name of the element to look for. |
public static Element getElement(Element root, String name)
//package com.java2s; /******************************************************************************* * Copyright (c) 2012 Firestar Software, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors://from w w w .j av a 2s . c om * Firestar Software, Inc. - initial API and implementation * * Author: * Gabriel Oancea * *******************************************************************************/ import org.w3c.dom.*; public class Main { /** * Get the first child element of the specified (root) element that has the specified name. If no element by the * specified name is found, null is returned. Note that more than one element with the same name may be a child of * root. This method simply returns the first one. * * @param root The element to search. * @param name The local name of the element to look for. * @return The element if found, null otherwise. */ public static Element getElement(Element root, String name) { if (root == null || name == null || name.length() <= 0) throw new IllegalArgumentException( "Null or invalid argument passed to XmlUtil.getElement()"); NodeList lst = root.getChildNodes(); int size = lst.getLength(); name = localName(name); for (int i = 0; i < size; i++) { Node node = lst.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { String nodeName = localName(node); if (name.equals(nodeName)) return (Element) node; } } return null; } /** * Get the local name of a node (that may have a prefix). For example <code>localName( "xsd:string" )</code> will * return <code>"string"</code> * * @param name A node name (normally a DOM Element). * @return The local part of the name. */ public static String localName(String name) { if (name == null || name.length() <= 0) return name; int p = name.indexOf(':'); if (p < 0 || p + 1 >= name.length()) return name; return name.substring(p + 1); } /** * Get the local name of a node (that may have a prefix). * * @param name The node (normally a DOM Element). * @return The local part of the name. */ public static String localName(Node node) { if (node == null) return null; String name = node.getLocalName(); if (name == null || name.length() <= 0) return localName(node.getNodeName()); return name; } }