Java XML Element Get from Parent getNamespacePrefix(Node parentNode, String preferredPrefix, String nsUri)

Here you can find the source of getNamespacePrefix(Node parentNode, String preferredPrefix, String nsUri)

Description

Traverse a node, and parent nodes, for a namespace URI.

License

Open Source License

Parameter

Parameter Description
parentNode - node from which to begin the search
preferredPrefix - Prefix to use if the namespace attribute must be created.
nsUri - the namesapce URI to search for

Return

the located/created namespace prefix

Declaration

public static String getNamespacePrefix(Node parentNode, String preferredPrefix, String nsUri) 

Method Source Code

//package com.java2s;
/*// w w  w .  jav a  2 s  . c o m
 * ? Copyright IBM Corp. 2012
 * 
 * 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.
 */

import org.w3c.dom.Document;

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

public class Main {
    /**
     * Traverse a node, and parent nodes, for a namespace URI. If the namespace
     * URI is located, the corresponding name is returned. If the namespace
     * uri is not located (i.e., does not exist), it is created as an attribute
     * node of the document root node.
     * @param parentNode - node from which to begin the search
     * @param preferredPrefix - Prefix to use if the namespace attribute must be created. 
     * @param nsUri - the namesapce URI to search for
     * @return the located/created namespace prefix
     */
    public static String getNamespacePrefix(Node parentNode, String preferredPrefix, String nsUri) {
        //traverse the list of namespaces
        Node currentNode = parentNode;
        do {
            NamedNodeMap nodeMap = currentNode.getAttributes();
            for (int i = 0; nodeMap != null && i < nodeMap.getLength(); i++) {
                Node item = nodeMap.item(i);
                String itemName = item.getNodeName();
                if (itemName.startsWith("xmlns")) { // $NON-NLS-1$
                    String uri = getTextValue(item);
                    if (nsUri.equals(uri)) {
                        return itemName.substring(itemName.indexOf(":") + 1);
                    }
                }
            }
        } while ((currentNode = currentNode.getParentNode()) != null);

        // If the namespace does not exist, then create it
        Element root = parentNode.getOwnerDocument().getDocumentElement();
        if (root != null) {
            for (int i = 1;; i++) {
                String p = preferredPrefix;
                if (i > 1) {
                    p += i;
                }
                if (root.getAttributeNode("xmlns:" + p) == null) { // $NON-NLS-1$
                    root.setAttribute("xmlns:" + p, nsUri); // $NON-NLS-1$
                    return p;
                }
            }
        }
        return "";
    }

    /**
     * Get the text associated with a node.
     * If case of an Element, then it concatenate all the Text parts into one big.
     * @return the text associated to the node
     */
    public static String getTextValue(Node node) {
        if (node != null) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if (node.hasChildNodes()) {
                    NodeList l = node.getChildNodes();
                    int len = l.getLength();
                    if (len == 1) {
                        Node child = l.item(0);
                        if (child.getNodeType() == Node.TEXT_NODE
                                || child.getNodeType() == Node.CDATA_SECTION_NODE) {
                            return child.getNodeValue();
                        }
                        return null;
                    } else {
                        StringBuilder b = new StringBuilder(128);
                        for (int i = 0; i < len; i++) {
                            Node child = l.item(i);
                            if (child.getNodeType() == Node.TEXT_NODE
                                    || child.getNodeType() == Node.CDATA_SECTION_NODE) {
                                String s = child.getNodeValue();
                                if (s != null) {
                                    b.append(s);
                                }
                            }
                        }
                        return b.toString();
                    }
                }
            } else if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE
                    || node.getNodeType() == Node.ATTRIBUTE_NODE) {
                return node.getNodeValue();
            }
        }
        return null;
    }

    /**
     * Return the owner document for the specified node.
     * 
     * @param node
     * @return
     */
    public static Document getOwnerDocument(Node node) {
        if (node instanceof Document) {
            return (Document) node;
        }
        return node.getOwnerDocument();
    }
}

Related

  1. getFirstElement(Node parent)
  2. getFirstElement(Node parent)
  3. getFirstNode(final Node parent, final String... path)
  4. getNamedElemValue(Element parent, String elementName)
  5. getNamedNodeList(Element parent, String containerTagName)
  6. getNameToFirstNode(Node parent, String node_name)
  7. getNameToNodeList(Node parent, String node_name)
  8. getNodeAtPosition(Node parent, int offset)
  9. getNodeBean(Node parent)