Java XML Element Namespace buildNamespacePrefixMap(final Element root)

Here you can find the source of buildNamespacePrefixMap(final Element root)

Description

Build Map of namespace URIs to prefixes.

License

Open Source License

Parameter

Parameter Description
root Element to get namespaces and prefixes from.

Return

of namespace URIs to prefixes.

Declaration

private static final Map<String, String> buildNamespacePrefixMap(final Element root) 

Method Source Code

//package com.java2s;

import java.util.HashMap;

import java.util.Map;

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

public class Main {
    /**//from  www  .  ja v  a  2  s.com
     * Build {@link Map} of namespace URIs to prefixes.
     * 
     * @param root
     *          {@link Element} to get namespaces and prefixes from.
     * @return {@link Map} of namespace URIs to prefixes.
     * @since 8.1
     */
    private static final Map<String, String> buildNamespacePrefixMap(final Element root) {
        final HashMap<String, String> namespacePrefixMap = new HashMap<>();

        //Look for all of the attributes of cache that start with
        //xmlns
        NamedNodeMap attributes = root.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node item = attributes.item(i);
            if (item.getNodeName().startsWith("xmlns")) {
                //Anything after the colon is the prefix
                //eg xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                //has a prefix of xsi
                String[] splitName = item.getNodeName().split(":");
                String prefix;
                if (splitName.length > 1) {
                    prefix = splitName[1];
                } else {
                    prefix = "";
                }
                String uri = item.getTextContent();
                namespacePrefixMap.put(uri, prefix);
            }
        }

        return namespacePrefixMap;
    }
}

Related

  1. addNamespaceDeclaration(Element element, String namespacePrefix, String namespaceURI)
  2. addNamespacePrefix(Element element, String namespaceUri, String prefix)
  3. buildNamespacePrefixMap(final Element root)
  4. byteArrayToElement(byte[] b, boolean namespaceAware)
  5. createElement(final String namespace, final String localPart, final String value)
  6. createElement(String namespaceURI, String name)