A Simple API for Parsing XML in Java

October 27, 2009

You can do a lot with XML, but often all you want to do is to read a simple file with some basic data in it. The options for doing this, SAX, DOM and JAXB are all relatively verbose and often off-putting. I’ve devised a simple XML API for parsing simple XML files in Java. Parsing a file such as:

<config>
	<title>test</title>
	<version
		major="1"
		minor="2"/>
	<roles>
		<role name="admin"/>
		<role name="user"/>
	</roles>
	<users>
		<user name="joe" password="pass" role="admin"/>
		<user name="harry" password="secret" role="user" email="harry@me.com"/>
	</users>
	<test/>
</config>

Can be achieved with the following code:

Xml config = new Xml("config.xml","config"); 
		
System.out.println("title: "+config.child("title").content());

Xml version = config.child("version");
System.out.println("version: "+version.integer("major")+"."+version.integer("minor"));

for(Xml role:config.child("roles").children("role")) 
	System.out.println("role: name: "+role.string("name"));

for(Xml user:config.child("users").children("user")) {
	String email = user.optString("email");
	System.out.println(
		"user: name: "+user.string("name")+
		", password: "+user.string("password")+
		", role: "+user.string("role")+
		", email: "+(email==null ? "-" : email));
}

System.out.println("test: "+config.option("test"));

Output:

title: test
version: 1.2
role: name: admin
role: name: user
user: name: joe, password: pass, role: admin, email: -
user: name: harry, password: secret, role: user, email: harry@me.com
test: true

As you can see, it’s nice and simple and allows you to get to the information quickly and without any hassle. The API uses the DOM parser underneath, but attempts to make the data more easily available. All you need is this class, which you can of course customise however you like.

About these ads

12 Responses to “A Simple API for Parsing XML in Java”

  1. Rahul Jaiswal Says:

    Hi,
    Thanks a lot for posting this information. It is really very helpful to accelerate me on XML document.
    I was planing to make such API but you have made my way too easy.
    Thanks again…

  2. me Says:

    thank you for your great article… but i am getting stuck with this xml:
    ————————————

    La început, Dumnezeu a făcut cerurile şi pămîntul.
    Pămîntul era pustiu şi gol; peste faţa adîncului de ape era întunerec, şi Duhul lui Dumnezeu se mişca pe deasupra apelor.

    ————————————

    i can’t parse it anyway…
    would you please help?

    ==============================
    int bookNumber = 3-1;
    int versNumber = 100-1;
    int until = 50;
    String versNumberLabel = “”;
    String verseText = “”;

    Document messageDom = XMLParser.parse(bible.xml);
    Node versNode = messageDom.getElementsByTagName(“VERS”).item(versNumber);
    while (versNumber < until) {
    versNode = messageDom.getElementsByTagName("VERS").item(versNumber);
    versNumberLabel = ((Element) versNode).getAttribute("vnumber");
    verseText += " |" + versNumberLabel + "| " + ((Element) versNode).getFirstChild().getNodeValue();
    versNumber++;
    }
    ==============================

  3. me Says:

    ==================xml====================

    La început, Dumnezeu a făcut cerurile şi pămîntul.
    Pămîntul era pustiu şi gol; peste faţa adîncului de ape era întunerec, şi Duhul lui Dumnezeu se mişca pe deasupra apelor.

    ==================xml====================

    http://pastebin.com/m674b67c5

  4. Federico Bazán Says:

    Hi, is very useful! Do you know if this code can be made with j2me?

    Thanks a lot.

    • argonrain Says:

      Hi, I’m glad you found it useful.
      Unfortunately I don’t think this code will work with J2ME because it uses the DOM parser and I don’t think this is available in J2ME.

  5. Barbara Regan Says:

    Thank you for posting this code. It has been very helpful. I like the simplicity and the fact that it actually works.

  6. Mark Kinsel Says:

    Thanks for the code. I’m trying to use it in an Android program related to dairies that I’m writing, but am running into difficulties since it uses the same names for classes and objects (e.g. Xml) as other built-in types. The XML file I am trying to read has the following structure:

    Example Farms
    Good Cows
    Jake’s Pen
    Bad Cows

    Demo Dairy
    Pen 1
    Pen 2
    Pen 3

    12/31/2011
    1321
    Our User
    79029

    I need to pull the attributes as well as the text. I’m new to Java and Android, so any help would be greatly appreciated. I’ve worked for years in Delphi and VB 2005. – Mark

    • argonrain Says:

      Hello,
      You should be able to use this in Android. If you are expiencing name clashes with the Android Xml class then either make sure you do not import android.util.Xml, or simply rename this Xml class to MyXml or something.
      To read attributes use the string() or integer() methods and pass the name of the attribute that you want. To get the content use the content() method. Have a look at my example.

  7. Mark Kinsel Says:

    Oops, the system converted my XML to straight text. Can anyone tell me how to post XML data including the tags that won’t be converted to just the content?

  8. argonrain Says:

    You can enclose your XML in the “sourcecode” tags:

    [sourcecode language="xml"]
    <a>
      <b>
        ...
      </b>
    </a>
    

    [/sourcecode]

    It’s difficult to post it because it also changes my post!


  9. Nice coding – thank you. You don’t have any license information on your page? Can you confirm that I can use your XML parser in a OpenSource project under an Apache 2,0 license? I will publish the final project on OpenNTF.org, with a backlink & credits to you.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: