lookup XML Namespace Prefix - Java XML

Java examples for XML:Namespace

Description

lookup XML Namespace Prefix

Demo Code

/*******************************************************************************
 * Copyright (c) 2006, 2010 Soyatec (http://www.soyatec.com) and others.
 * 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  a v a 2 s  . c om
 *     Soyatec - initial API and implementation
 *******************************************************************************/
//package com.java2s;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    public static String XMLNS = "xmlns";

    public static String lookupNamespacePrefix(Node node, String namespace) {
        NamedNodeMap map = node.getAttributes();
        if (map != null && map.getLength() > 0) {
            for (int i = 0; i < map.getLength(); i++) {
                Node attr = map.item(i);
                String name = attr.getNodeName();
                if (name.startsWith(XMLNS)
                        && namespace.equals(attr.getNodeValue())) {
                    int index = name.indexOf(':');
                    if (index == -1) {
                        return "";
                    }
                    return name.substring(index + 1);
                }
            }
        }

        Node nodeParent = node.getParentNode();
        if (nodeParent != null) {
            return lookupNamespacePrefix(nodeParent, namespace);
        }
        return null;
    }
}

Related Tutorials