Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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

share|improve this question
 
If you don't have to use Java, you can use the hxselect tool from: w3.org/Tools/HTML-XML-utils –  Dave Jarvis May 30 at 18:05
add comment

2 Answers

up vote 2 down vote accepted

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

share|improve this answer
add comment

I think you should look into using a different parser for this particular situation. this page contains good comparisons between java xml parsers. Maybe SAX or StAX is more suitable here?

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.