Java XML QName Get getQName(Element xml)

Here you can find the source of getQName(Element xml)

Description

Retrieves the text from the element specified and parses it into a fully-resolved QName.

License

Apache License

Parameter

Parameter Description
xml a parameter

Return

A fully-resolved QName, or null if there was no text.

Declaration

public static QName getQName(Element xml) 

Method Source Code

//package com.java2s;
/* //from  w ww .  j  av  a2 s .  co m
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 javax.xml.namespace.QName;

import org.w3c.dom.Element;

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

public class Main {
    /**
     * 
     * Standard prefix for XML namespace attributes.
     * 
     */
    public static final String XMLNS_PREFIX = "xmlns";

    /**
     * 
     * Retrieves the text from the element specified and parses it 
     * into a fully-resolved QName.
     *
     * @param xml
     * 
     * @return A fully-resolved QName, or null if there was no text.
     *
     */
    public static QName getQName(Element xml) {
        String qnameString = extractText(xml);

        if (qnameString == null)
            return null;

        return parseQName(qnameString, xml);
    }

    /**
     *
     * @param element
     *        The Element that may or may not have Text nodes.
     * 
     * @return The content of the first child Text node in the Element. The 
     *         method returns null if the Element has no text.
     *
     */
    public static String extractText(Element element) {
        NodeList children = element.getChildNodes();
        int length = children.getLength();

        //
        // have to check all nodes, because we could have text 
        // mixed with elements
        //
        for (int n = 0; n < length; ++n) {
            Node next = children.item(n);

            //
            // note that we remove all leading/trailing whitespace
            //
            if (next.getNodeType() == Node.TEXT_NODE)
                return next.getNodeValue().trim();
        }

        return null;
    }

    /**
     * 
     * Parses the given String into a QName object and resolves the prefix 
     * to a namespace URI. The search for a valid namespace URI starts with 
     * the given context Element and continues up to the root of the XML 
     * Document. If no matching namespace can be found, the QName will have 
     * a null namespace URI.
     *
     * @param qname
     *        The qualified name, in string form.
     * 
     * @param namespaceContext
     *        The Element from which to start namespace resolution. The 
     *        search will start with this Element and move up through its 
     *        parents until a match is found or the root is hit.
     * 
     * @return A QName object with a proper namespace URI, if one is defined.
     * 
     * @see #resolveNamespace(String, Node)
     *
     */
    public static QName parseQName(String qname, Element namespaceContext) {
        int colonIndex = qname.indexOf(':');

        String prefix = null;

        if (colonIndex >= 0)
            prefix = qname.substring(0, colonIndex);

        String localName = qname.substring(colonIndex + 1);

        String uri = null;

        //
        // if possible, try to resolve the prefix to a namespace URI
        //
        if (namespaceContext != null)
            uri = resolveNamespace(qname, namespaceContext);

        //
        // prefix is not required, but it CANNOT be null
        //
        if (prefix != null && prefix.length() > 0)
            return new QName(uri, localName, prefix);

        return new QName(uri, localName);
    }

    /**
     * 
     * Parses the prefix from the given qualified name and finds the first 
     * XML namespace declaration that maps that prefix to a namespace URI. 
     * If there is no prefix, the method searches for the 
     * <em>targetNamespace</em> attribute instead. The search starts with the 
     * give Node and moves up the XML Document until a match is found or the 
     * root of the Document is reached. 
     *
     * @param qname
     *        The qualified name whose prefix is searched for.
     * 
     * @param xml
     *        The Node from which namespace resolution will start.
     * 
     * @return The namespace URI that the QName's prefix is associated 
     *         with. The method returns null if no match is found.
     *
     */
    public static String resolveNamespace(String qname, Node xml) {
        int colonIndex = qname.indexOf(':');

        //
        // if no prefix is provided, we look for the target NS
        //
        String attributeName = XMLNS_PREFIX;

        if (colonIndex >= 0) {
            String prefix = qname.substring(0, colonIndex);
            attributeName += ':' + prefix;
        }

        //
        // go up the tree until we find something (or hit the root)
        //
        return searchParentNamespaces(xml, attributeName);
    }

    /**
     * 
     * Traverses up the XML Document tree looking for XML an namespace 
     * declaration that matches the given attribute.
     *
     * @param xml
     *        The Node to start the search from. The search will move up 
     *        through the parents of this Node.
     * 
     * @param attribute
     *        The name of the XML namespace attribute to search for. This 
     *        should be <em>xmlns:prefix</em> or <em>targetNamespace</em>.
     * 
     * @return The first value found for the given attribute. The method 
     *         returns null if the attribute is not found in the given Node 
     *         or its parents.
     *
     */
    private static String searchParentNamespaces(Node xml, String attribute) {
        Node next = xml;
        String uri = null;

        //
        // go up the tree until we find a matching prefix/URI (or hit the top)
        //
        while (next != null && (uri == null || uri.length() == 0)) {
            if (next.getNodeType() == Node.ELEMENT_NODE)
                uri = ((Element) next).getAttribute(attribute);

            next = next.getParentNode();
        }

        //
        // DOM returns empty strings for non-existent attributes - we want null
        //
        if (uri != null && uri.length() == 0)
            uri = null;

        return uri;
    }
}

Related

  1. getName(QName qName)
  2. getName(QName qname)
  3. getQName(@Nonnull final Element aElement)
  4. getQName(Class klass)
  5. getQName(Element el)
  6. getQName(final String name)
  7. getQName(Node n)
  8. getQName(Node node)
  9. getQName(Node node)