2

Consider the following XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>

I would like to parse this XML and print the following to stdout:

Bob Dylan recorded Empire Burlesque in 1985.
Bonnie Tyler recorded Hide your heart in 1988.

Whats the easiest way to do this in Java?

I'm frustrated because I can parse this XML in 5 or 6 lines in some languages, but in Java the only method I know of is to write my own SAX parser, meaning I'll need around 50 lines of code; 10 times what I might use elsewhere! Does Java have a super simple XML parser suitable for easy tasks like this?

(I know there are similar questions, but they either don't contain an example, or the example involves long, partial, and/or deeply nested XML. This question has a simple example, and hopefully will receive some good answers with working code to distinguish it.)

Buttons840
  • 9,239
  • 15
  • 58
  • 85
  • 1
    possible duplicate of [Best XML parser for Java](http://stackoverflow.com/questions/373833/best-xml-parser-for-java) – assylias May 22 '12 at 18:10
  • What about not using Java? You won't be able to parse this file in java in 5 lines of code. – Maurício Linhares May 22 '12 at 18:10
  • 3
    Have you looked at the bundled api's or other libs to parse XML? http://en.wikipedia.org/wiki/Java_API_for_XML_Processing or http://www.mkyong.com/tutorials/java-xml-tutorials/ – scrappedcola May 22 '12 at 18:12
  • 1
    This is a good question, why close it? Having an easy way of parsing XML with one line of code in Java is problematic and should be discussed. – Faustas Nov 08 '13 at 17:34

1 Answers1

2

Try XOM.

    import nu.xom.*;

    List<Element> cds = new Builder().build(inputFile).getRootElement().query("CD");
    for (Element e : cds) {
        System.out.println(e.getFirstChildElement("ARTIST").getValue() 
            + " recorded " 
            + e.getFirstChildElement("TITLE").getValue() 
            + " in " 
            + e.getFirstChildElement("YEAR").getValue());
    }
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276