3
\$\begingroup\$

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

\$\endgroup\$
0
5
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ Hello @joe-f, the link to the article is broken, can you update it please? \$\endgroup\$ – Sergiy Sokolenko Apr 2 '15 at 6:50
1
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

You can typecast the node to Element and then use getAttribute. Eg:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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