Java examples for XML:XML Attribute
A method to get attribute value from provided xml node and attribute name
//package com.java2s; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; public class Main { /**//from w w w. j a v a2 s. c o m * A method to get attribute value from provided xml node and attribute name * @param Node parent, a node where the attribute residing * @param String attr, attribute name to get * @return String , a value from request attribute */ static public String getAttribute(Node parent, String Attr) { String ret = ""; if (!parent.hasAttributes()) return (""); NamedNodeMap nmap = parent.getAttributes(); for (int i = 0; i < nmap.getLength(); ++i) { Node n = nmap.item(i); if (n.getNodeName().trim().equals(Attr)) { ret = n.getNodeValue().trim(); } //System.out.println("Attribute: "+n.getNodeType()+" - "+n.getNodeName()+" "+n.getNodeValue()); } return (ret); } /** * A method to get the value of desire node from xml document * @param Node parent, xml's node object to get * @return String , value from provided node */ static public String getNodeValue(Node parent) { String ret = ""; Node n = parent.getFirstChild(); while (n != null) { if (n.getNodeType() == Node.TEXT_NODE) { try { ret = n.getNodeValue().trim(); } catch (NullPointerException ex) { ret = ""; break; } } n = n.getNextSibling(); } return (ret); } }