HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Better way to get the XML attribute value?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thewayxmlbettervaluegetattribute

Problem

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)?

Solution

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);


There is a lot more information in this article: http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html

Code Snippets

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);

Context

StackExchange Code Review Q#26790, answer score: 5

Revisions (0)

No revisions yet.