tags:

views:

359

answers:

6

I need to just read the value of a single attribute inside an XML file using java. The XML would look something like this:

<behavior name="Fred" version="2.0" ....>

and I just need to read out the version. Can someone point in the direction of a resource that would show me how to do this?

+1  A: 

Here's one.

import javax.xml.parsers.SAXParser;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;
import javax.xml.parsers.SAXParserFactory;

/**
 * Here is sample of reading attributes of a given XML element.
 */

public class SampleOfReadingAttributes {
    /**
     * Application entry point
     * @param args command-line arguments
     */
    public static void main(String[] args) {
        try {
            // creates and returns new instance of SAX-implementation:
            SAXParserFactory factory = SAXParserFactory.newInstance();

            // create SAX-parser...
            SAXParser parser = factory.newSAXParser();
            // .. define our handler:
            SaxHandler handler = new SaxHandler();

            // and parse:
            parser.parse("sample.xml", handler);

        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }

    /**
     * Our own implementation of SAX handler reading
     * a purchase-order data.
     */
    private static final class SaxHandler extends DefaultHandler {

        // we enter to element 'qName':
        public void startElement(String uri, String localName,
                String qName, Attributes attrs) throws SAXException {

            if (qName.equals("behavior")) {
                // get version
                String version = attrs.getValue("version");


                System.out.println("Version is " + version );

            }
        }
    }
}
seth
I'd use this approach if I was on JSE5, but the javax.xml.stream API in Java 6 and JEE lets you quit parsing after the first element without resorting to artificial mechanisms like throwing an exception.
McDowell
Boy, this is complicated. Creating a SAXParserFactory, a SAXParser, and a custom SaxHandler just to execute "//behaviour" is a lot of work.
A: 

If all you need is to read the version, then you can use regex. But really, I think you need apache digester

serge_bg
XML + regext = flame bait :) But I agree with your recommendation of apache digester.
+1  A: 

As mentioned you can use the SAXParser.

Digester mentioned using regular expressions, which I won't recommend as it would lead to code that is difficult to maintain: What if you add another version attribute in another tag, or another behaviour tag? You can handle it, but it won't be pretty.

You can also use XPath, which is a language for querying xml. That's what I would recommend.

Kolibri
+1  A: 

JAXB for brevity:

  private static String readVersion(File file) {
    @XmlRootElement class Behavior {
      @XmlAttribute String version;
    }
    return JAXB.unmarshal(file, Behavior.class).version;
  }

StAX for efficiency:

  private static String readVersionEfficient(File file)
      throws XMLStreamException, IOException {
    XMLInputFactory inFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlReader = inFactory
        .createXMLStreamReader(new StreamSource(file));
    try {
      while (xmlReader.hasNext()) {
        if (xmlReader.next() == XMLStreamConstants.START_ELEMENT) {
          if (xmlReader.getLocalName().equals("behavior")) {
            return xmlReader.getAttributeValue(null, "version");
          } else {
            throw new IOException("Invalid file");
          }
        }
      }
      throw new IOException("Invalid file");
    } finally {
      xmlReader.close();
    }
  }
McDowell
That JAXB version is rather disturbing in terms of overhead. :)
Steven Huwig
A: 

Apache Commons Configuration is nice, too. Commons Digester is based on it.

+3  A: 

You don't need a fancy library -- plain old JAXP versions of DOM and XPath are pretty easy to read and write for this. Whatever you do, don't use a regular expression.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class GetVersion {
    public static void main(String[] args) throws Exception {
        XPath xpath = XPathFactory.newInstance().newXPath();
        Document doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse("file:////tmp/whatever.xml");
        String version = xpath.evaluate("//behavior/@version", doc);
        System.out.println(version);
    }
}
Steven Huwig