Java XML Attribute Get getAttribute(String attribute, Node node)

Here you can find the source of getAttribute(String attribute, Node node)

Description

Convenience for accessing an attribute value (the Node interface is rather ugly)

License

Open Source License

Parameter

Parameter Description
attribute a parameter
node a parameter

Return

value or null

Declaration

public static String getAttribute(String attribute, Node node) 

Method Source Code

//package com.java2s;

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

public class Main {
    /**//from   w ww  .  j av a  2  s. c o  m
     * Convenience for accessing an attribute value (the Node interface is
     * rather ugly)
     *
     * @param attribute
     * @param node
     * @return value or null
     */
    public static String getAttribute(String attribute, Node node) {
        NamedNodeMap att = node.getAttributes();
        Node w = att.getNamedItem(attribute);
        if (w == null)
            return null;
        return w.getTextContent();
    }

    /**
     * FIXME problems in the following situation:
     * getAttribute("href","<a href=abc.com >woo</a>")
     *
     * Crude XML tag parser: rips the attribute value out using a text scan. NB:
     * Attributes must be quoted
     *
     * @param attribute
     * @param tag
     * @return attribute-value or null
     */
    public static String getAttribute(String attribute, String tag) {
        attribute += '=';
        int i = tag.indexOf(attribute);
        if (i == -1)
            return null;
        i += attribute.length();
        if (i == tag.length())
            return null;
        // fail? 
        int closed = tag.indexOf('>');
        if (i > closed) {
            // The attribute is in a sub-tag, so doesn't count
            return null;
        }
        char q = tag.charAt(i);
        // quoted
        if (q == '"' || q == '\'') {
            for (int j = i + 1; j < tag.length(); j++) {
                char c = tag.charAt(j);
                // FIXME escaping chars
                if (c == q) {
                    return tag.substring(i + 1, j);
                }
            }
        } else {
            // unquoted
            for (int j = i; j < tag.length(); j++) {
                char c = tag.charAt(j);
                if (Character.isWhitespace(c) || '>' == c)
                    return tag.substring(i, j);
            }
        }
        throw new IllegalArgumentException(tag + " is not valid xml");
    }
}

Related

  1. getAttribute(Node pNode, String attrName)
  2. getAttribute(Node pNode, String pName)
  3. getAttribute(Node targetElem, String keyName, String defaultValue)
  4. getAttribute(String aAttrName, Node aNode)
  5. getAttribute(String attribute, Node node)
  6. getAttribute(String attribute, Node node)
  7. getAttribute(String key, NamedNodeMap map)
  8. getAttribute(String name, Element el)
  9. getAttribute(String name, Element element)