# Better way to get the XML attribute value?

I have an xml file from which I want to extract the value of attribute custName from the very first child. The code below works where I am using the dom parser. Is there a third-party library with which I can do the same with less code and more neatly?

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = (Document) db.parse(new File(
tempDir));
Node node = ((Document) document).getFirstChild();
String custName= node.getAttributes()
.getNamedItem("custName")
.getNodeValue();
assertEquals( "scott",custName);


Update:- Did the above approach use DOM4J (sorry but I am not sure)?

You could use the Java XPath API:

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

XPath xpath = XPathFactory.newInstance().newXPath();
InputSource inputSource = new InputSource(???); // ??? = InputStream or Reader
String custName = xpath.evaluate("//*[1]/@custName", inputSource);


String attributeValue = ((Element)yourNode).getAttribute("yourAttribute");