Java XML Attribute Set attr(Element element, String name)

Here you can find the source of attr(Element element, String name)

Description

Get an attribute value if it exists, or null

License

Apache License

Declaration

static final String attr(Element element, String name) 

Method Source Code

//package com.java2s;
/**/*from w ww . j  a  v  a2  s. c o m*/
 * Copyright (c) 2011-2016, Data Geekery GmbH (http://www.datageekery.com)
 *
 * 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.Element;
import org.w3c.dom.NamedNodeMap;

public class Main {
    /**
     * Get an attribute value if it exists, or <code>null</code>
     */
    static final String attr(Element element, String name) {
        return attr(element, name, true);
    }

    /**
     * Get an attribute value if it exists, or <code>null</code>
     */
    static final String attr(Element element, String name, boolean ignoreNamespace) {
        NamedNodeMap attributes = element.getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {
            String localName = attributes.item(i).getNodeName();

            // [#103] If namespaces are ignored, consider only local
            // part of possibly namespace-unaware Element
            if (ignoreNamespace) {
                localName = stripNamespace(localName);
            }

            if (name.equals(localName)) {
                return attributes.item(i).getNodeValue();
            }
        }

        return null;
    }

    static String stripNamespace(String tagName) {
        int index = tagName.indexOf(':');

        if (index > -1) {
            return tagName.substring(index + 1);
        }

        return tagName;
    }
}

Related

  1. attr(Element element, String name)
  2. attrbiuteToMap( NamedNodeMap attributes)
  3. attribute(Element element, String attrName)
  4. attribute(Node node, String... attributes)