Java tutorial
//package com.java2s; import org.w3c.dom.traversal.NodeFilter; import org.w3c.dom.*; public class Main { /** * Get attribute value, returning <code>null</code> if unset. * Some DOM implementations return an empty string for an unset * attribute. * @param element The DOM element. * @param attributeName The attribute to get. * @return The attribute value, or <code>null</code> if unset. */ public static String getAttributeValue(Element element, String attributeName) { return getAttributeValue(element, attributeName, null); } /** * Get attribute value, returning <code>null</code> if unset. * Some DOM implementations return an empty string for an unset * attribute. * @param element The DOM element. * @param attributeName The attribute to get. * @param namespaceURI Namespace URI of the required attribute, or null * to perform a non-namespaced get. * @return The attribute value, or <code>null</code> if unset. */ public static String getAttributeValue(Element element, String attributeName, String namespaceURI) { String attributeValue; if (namespaceURI == null) { attributeValue = element.getAttribute(attributeName); } else { attributeValue = element.getAttributeNS(namespaceURI, attributeName); } if (attributeValue.length() == 0 && !element.hasAttribute(attributeName)) { return null; } return attributeValue; } public String getAttributeValue(Element element, Node attr, NodeFilter attrFilter) { if (attrFilter == null || attrFilter.acceptNode(attr) != -1) { String value = getXMLString(attr.getNodeValue()); String quat = "\""; if (value.indexOf("\"") > 0) { quat = "'"; } return " " + attr.getNodeName() + "=" + quat + value + quat; } return ""; } /** * Get an Attribute from an Element. Returns an empty String if none found * http://www.java2s.com/Code/Java/XML/ReturnalistofnamedElementswithaspecificattributevalue.htm * @param element the containing Element. * @param name the attribute name. * @return Attribute as a String. */ public static String getAttribute(Element element, String name) { return element.getAttribute(name); } public String getXMLString(String targetS) { return targetS.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); } }