Java XML Attribute Get getAttributeValue(Element ele, String attrName)

Here you can find the source of getAttributeValue(Element ele, String attrName)

Description

Helper function for quickly retrieving an attribute from a given element.

License

Open Source License

Parameter

Parameter Description
ele The document element from which to pull the attribute value.
attrName The name of the attribute.

Return

The value of the attribute contained within the element

Declaration

public static String getAttributeValue(Element ele, String attrName) 

Method Source Code

//package com.java2s;
import org.w3c.dom.Element;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern encgt = Pattern.compile(">");
    private static final Pattern enclt = Pattern.compile("<");
    private static final Pattern encQuot = Pattern.compile(""");
    private static final Pattern encAmp = Pattern.compile("&");

    /**//from w w w.  j a v a2  s  .c  o m
     * Helper function for quickly retrieving an attribute from a given
     * element. 
     * @param ele The document element from which to pull the attribute value.
     * @param attrName The name of the attribute.
     * @return The value of the attribute contained within the element
     */
    public static String getAttributeValue(Element ele, String attrName) {
        return decode(ele.getAttribute(attrName));
    }

    /**
     * Helper function for decode XML entities.
     *
     * @param str The XML-encoded String to decode.
     * @return An XML-decoded String.
     */
    public static String decode(String str) {

        if (str == null) {
            return null;
        }

        Matcher gtmatcher = encgt.matcher(str);
        if (gtmatcher.matches()) {
            str = gtmatcher.replaceAll(">");
        }
        Matcher ltmatcher = enclt.matcher(str);
        if (ltmatcher.matches()) {
            str = ltmatcher.replaceAll("<");
        }
        Matcher quotMatcher = encQuot.matcher(str);
        if (quotMatcher.matches()) {
            str = quotMatcher.replaceAll("\"");
        }
        Matcher ampMatcher = encAmp.matcher(str);
        if (ampMatcher.matches()) {
            str = ampMatcher.replaceAll("&");
        }

        return str;
    }
}

Related

  1. getAttributeValue(Element e, String key)
  2. getAttributeValue(Element e, String name)
  3. getAttributeValue(Element el, String attributeName)
  4. getAttributeValue(Element el, String attributeName)
  5. getAttributeValue(Element el, String attrName)
  6. getAttributeValue(Element elem, String name)
  7. getAttributeValue(Element element, String attr)
  8. getAttributeValue(Element element, String attributeName)
  9. getAttributeValue(Element element, String attributeName, String namespaceURI)