This is my simple XML Utils library. It's a tiny (10k) Java library that takes advantage of modern Java features like generics and var args to give you a simple an convenient API for parsing and generating XML. It is not the fastest or most feature complete XML solution, but it gives you very clean code and lets you drop down to standard Java APIs when you want to.
version 0.1 download: jar docs source
The XMLWriter class provides methods start() and end() to generate nested XML elements. start() has var args to let you set an unlimited number of attributes on your element. Ex: to write out the element foo with attributes version=0.01 and type=bar, do the following:
out.start("foo","version","0.01","type","bar");
XMLWriter also uses method chaining to let you start and end an element on the same line. Here is a complete XML of generating XLM to the foo.xml file with a standard XML header, var args, and method chaining:
XMLWriter out = new XMLWriter(new File("foo.xml"));
out.header(); //standard xml header
out.start("foo", "version","0.01","type","bar");
for(int i=0; i<3; i++) {
out.start("bar","id",""+i).end();
}
out.end();
out.close();
produces:
contents of foo.xml
<?xml version="1.0"?>
<foo
version='0.01'
type='bar'
>
<bar
id='0'
>
</bar>
<bar
id='1'
>
</bar>
<bar
id='2'
>
</bar>
</foo>
The XMLParser uses a DOM Parser and XPath to extract the parts of the document you want. Combined with generics and iterators you can conveniently parse your XML in a loop. For example, to parse the document from the previous example back in, grabbing all of the 'bar' elements, then print out their ID attributes:
Doc doc = XMLParser.parse(new File("foo.xml"));
for(Elem e : doc.xpath("//bar")) {
System.out.println("id = " + e.attr("id"));
}
This XML library uses the standard W3C Dom and javax.xml parsers underneath. Each DOM element is wrapped by a custom class with the convenience methods. Only elements returned from an XPath query are wrapped, so if you skip most of the document then most of it will never get wrapped.
This code is licensed under the BSD license. Use it for whatever you wish. Copyright Josh Marinacci, 2010. Note, this project is completely independent from my employer's work, and expresses nothing about my employer's desires, plans, or roadmap.