Get the first child with the specified name in the specified namespace. - Java XML

Java examples for XML:Namespace

Description

Get the first child with the specified name in the specified namespace.

Demo Code

/**// w ww.j a  v  a 2s  .c o  m
 * Copyright (c) 2009 DITA2InDesign project (dita2indesign.sourceforge.net)  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. 
 */
//package com.java2s;

import org.w3c.dom.Element;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Get the first child with the specified name in the specified namespace.
     * @param elem Parent to get the child of
     * @param namespaceUri Namespace URI. Cannot be null (use getElement() to get no-namespace elements)
     * @param localName Local part of tagname.
     * @return First element with specified name or null
     */
    public static Element getElementNS(Element elem, String namespaceUri,
            String localName) {
        NodeList nl = elem.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if ((node.getNamespaceURI() != null && node
                        .getNamespaceURI().equals(namespaceUri))
                        && node.getLocalName().equals(localName)) {
                    return (Element) node;
                }
            }
        }
        return null;
    }
}

Related Tutorials