Parse namespace prefixes defined in the XML documents root element. - Java XML

Java examples for XML:DOM Document

Description

Parse namespace prefixes defined in the XML documents root element.

Demo Code

/**//  ww w  . j ava 2s . c  o  m
 *  Copyright 2012 Sven Ewald
 *
 *  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 java.util.HashMap;

import java.util.Map;
import javax.xml.XMLConstants;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    /**
     * Parse namespace prefixes defined in the documents root element.
     *
     * @param document
     *            source document.
     * @return map with prefix->uri relationships.
     */
    public static Map<String, String> getNamespaceMapping(
            final Document document) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("xmlns", "http://www.w3.org/2000/xmlns/");
        map.put("xml", "http://www.w3.org/XML/1998/namespace");
        //      if (childName.equals("xmlns") || childName.startsWith("xmlns:")) {
        //      return "http://www.w3.org/2000/xmlns/";
        //  }
        //  if (childName.startsWith("xml:")) {
        //      return "http://www.w3.org/XML/1998/namespace";
        //  }

        Element root = document.getDocumentElement();
        if (root == null) {
            // No document, no namespaces.
            return map;
        }
        NamedNodeMap attributes = root.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if ((!XMLConstants.XMLNS_ATTRIBUTE
                    .equals(attribute.getPrefix()))
                    && (!XMLConstants.XMLNS_ATTRIBUTE.equals(attribute
                            .getLocalName()))) {
                continue;
            }
            if (XMLConstants.XMLNS_ATTRIBUTE.equals(attribute
                    .getLocalName())) {
                map.put("xbdefaultns", attribute.getNodeValue());
                continue;
            }
            map.put(attribute.getLocalName(), attribute.getNodeValue());
        }
        return map;
    }
}

Related Tutorials