Returns the XML attribute value or defaultValue if it does not exist. - Java XML

Java examples for XML:XML Attribute

Description

Returns the XML attribute value or defaultValue if it does not exist.

Demo Code


//package com.java2s;

import org.w3c.dom.Element;

public class Main {
    /**/*  w w  w  . jav a  2  s .  c  om*/
     * Returns the attribute value or {@code defaultValue} if it does not exist.
     */
    public static String getAttribute(Element element, Enum<?> attribute,
            String defaultValue) {
        final String value = getAttribute(element, attribute);
        if (value != null) {
            return value;
        }
        return defaultValue;
    }

    /**
     * Returns the attribute value or {@code null} if it does not exist.
     */
    public static String getAttribute(Element element, Enum<?> attribute) {
        final String attName = getXmlName(attribute);
        final String attValue = element.getAttribute(attName);
        return attValue == null || attValue.isEmpty() ? null : attValue;
    }

    public static String getXmlName(Enum<?> node) {
        String name = node.name();

        //remove leading or trailing underscore, it is used if a name conflicts with a Java keyword
        if (name.length() > 0 && name.charAt(0) == '_') {
            name = name.substring(1);
        }
        if (name.length() > 0 && name.charAt(name.length() - 1) == '_') {
            name = name.substring(0, name.length() - 1);
        }
        return name.replace('_', '-');//use dashes instead of underscores in XML
    }
}

Related Tutorials