Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Parsing a read-only XML file with JDOM

From: Android SDK: Local Data Storage

Video: Parsing a read-only XML file with JDOM

I've previously described how to parse XML files using the XML Pull Parser, a streaming parser that's included with the Android SDK. I'm now going to describe an alternative approach using a parser called JDOM. JDOM is a third-party open-source, free solution that works well in both generic Java applications and in Android apps. You can download the binaries for JDOM, but I've included the JAR file. That is the library that you need to include in your application in the exercise files.

Parsing a read-only XML file with JDOM

I've previously described how to parse XML files using the XML Pull Parser, a streaming parser that's included with the Android SDK. I'm now going to describe an alternative approach using a parser called JDOM. JDOM is a third-party open-source, free solution that works well in both generic Java applications and in Android apps. You can download the binaries for JDOM, but I've included the JAR file. That is the library that you need to include in your application in the exercise files.

I'll get out of the browser and I'll go to my Exercise Files folder. Under the Assets folder, there's a subfolder called Software, and there's a file there called jdom-2.0.3.jar. You can use this or any later version. I'll copy the JAR file to the clipboard. Then I'll go back to Eclipse. Within Eclipse, I'll go to the libs folder of my new project, XMLJDOMParser. I'll go to that libs folder and I'll paste the file into place.

In addition to adding the JAR file to the libs folder, you can also explicitly add the JAR file to the build path for the application, and that will ensure that the JAR file is exported with the application. I'll right-click on the JAR file. Then I'll go to the Build Path menu choice and choose Add to Build Path. That adds JDOM to the referenced libraries for the application. I'm ready for some code. In the existing version of the application, I'm using the ToursPullParser class, a class I created that parses the file with the XML Pull Parser and streams through the file, listening to events for various tags.

As I've described, the code for this parser is somewhat fragmented. You have to keep track of where you are in the streaming and then write conditional logic to handle each of the elements. The reason to use JDOM is because it will significantly decrease the amount of code that you need to write and the fragmentation of that code. As with the XML Pull Parser, I've created a class that uses JDOM. I'll move Eclipse over to the right and go to my exercise files, and I'll go to my Assets folder and from there, to code.

I'll choose this file: ToursJDOMParser.java. I'll copy it to the clipboard. Then I'll return to Eclipse and I'll make it full screen again. I'll close down the Pull Parser class, and I'll paste my new class into the project's default package. Here's the JDOM parser code. Just as with the Pull Parser, it starts by creating some constants.

With JDOM, in addition to the elements for each minor data element, you'll need to define a tag name for the major data element--that is, for the tour--and I've done that right here. Just as with the pull parser class, I've created a method called parseXML, and then I'm using the context that's passed in that points to the current activity and current application, and I'm opening the tours XML file, using its resource ID. For JDOM, I'm creating an InputStream and then passing that to something called a SAXBuilder.

JDOM includes both a DOMBuilder-- that stands for Document Object Model-- and a SAXBuilder, the simple API for XML. Comparing SAX with DOM is a matter of performance and memory management. With DOM, or Document Object Model, the entire XML document is always stored in memory all at the same time. In contrast, the SAXBuilder uses streaming, in a process that's very similar to the XML Pull Parser. What JDOM gives you though is that it hides that process in the background and makes it feel like you have the entire document in memory at all times.

Just as with the PullParser class, I'm creating a list of tour objects, and then I'm ready to parse. Using JDOM, I create a document object. This is a document object that's specific to JDOM, and it's a part of the org.jdom2 package. I get that document object by calling a method called build, passing in a stream that's pointing to the XML file. Then I get a reference to the rootNode of the document. I'm doing that, calling a method called getRootElement.

That returns an instance of the Element class. Notice when I'm working with the JDOM element class I'm having to explicitly name the entire package. That's because there's an element class that's a part of the Android SDK that otherwise would collide. Then I'm creating a list containing an instance of that element class, and I'm doing that by calling a method called getChildren and passing in the name of the tag that contains each tour. So now, I have a list of tours in memory.

Now, I'm looping through the list. I'm using a for-each-style loop. I'm saying for each node in the list, create a new tour object, then go get the data for each of the data elements: the tour ID, the tour title, description, and so on. The tour ID is being parsed into an integer, the tour price into a double, and all the other values are string, or text, values. Then I'm taking all that data packaged up as a tour object and adding it to the list.

Finally, at the end of try block I'm returning the tours object. Unlike the PullParser class, there isn't any other code. This is it. The nature of DOM programming is that it allows you to put all your code in a single place and say, I want to get this field and I want to get that field. And the mechanics of parsing the XML file are hidden from you. It's a simpler programming model, and it takes a lot less code to do the work. Depending on your device and the nature of your XML file, it might even be faster.

If you're not sure whether this is the right approach for you, based on performance, I encourage you to do your own benchmarking. But this class is now a part of our project. So switching from the XML Pull Parser to the JDOM Parser will be a simple matter of changing which class we're using. I'll go back to my Package Explorer and open up my MainActivity. I'll go to the bottom of the onCreate method and I'll change the parser that I'm using. I'll duplicate this line of code, and then I'll change from ToursPullParser to ToursJDOMParser.

I'll change it both in the variable declaration and in the constructor method call. I'll comment out the version that's creating the PullParser object and everything else is exactly the same. I'll save my changes and I'll run the application in the emulator. When the application opens, I'll see that the data is retrieved, parsed, and displayed, looking exactly the same as it did before. Just as with the pull parser, I'm getting back a list of tour objects, and I'm depending on the toString method of the tour class to determine how the data is displayed in each list item.

So, it's your choice. The XML Pull Parser is a tool that's a part of the Android SDK, whereas JDOM has to be added to your application and will add a little bit to the size of your final app. But the JDOM parsing model is a lot cleaner and results in a lot less code. Either of these parsers will do the job, parsing XML and delivering the data to your users.

Show transcript

This video is part of

Image for Android SDK: Local Data Storage
Android SDK: Local Data Storage

29 video lessons · 5890 viewers

David Gassner
Author

 
Expand all | Collapse all
  1. 6m 34s
    1. Welcome
      50s
    2. What you should know before starting this course
      2m 11s
    3. Using the exercise files
      3m 33s
  2. 21m 6s
    1. Exploring local data storage options
      5m 58s
    2. Configuring Eclipse and the Android Developer Tools
      5m 29s
    3. Creating an Android virtual device
      3m 23s
    4. Creating a new Android project
      6m 16s
  3. 31m 30s
    1. Using preferences in Android apps
      5m 28s
    2. Defining preferences with Java
      9m 31s
    3. Defining shared preferences with an activity
      10m 50s
    4. Listening for changes to shared preferences
      5m 41s
  4. 51m 13s
    1. Creating and reading files in internal storage
      10m 18s
    2. Creating and reading JSON data files
      9m 48s
    3. Working with files in external storage
      11m 22s
    4. Parsing a read-only XML file with XmlPullParser
      11m 46s
    5. Parsing a read-only XML file with JDOM
      7m 59s
  5. 1h 8m
    1. Creating a new SQLite database
      2m 52s
    2. Defining a database with SQLiteOpenHelper
      12m 12s
    3. Managing the database with a DataSource class
      9m 38s
    4. Inserting data into a database table
      10m 29s
    5. Retrieving and displaying data
      11m 44s
    6. Importing data from XML to SQLite
      5m 15s
    7. Filtering and sorting data
      9m 27s
    8. Accessing a database from the command line
      6m 46s
  6. 42m 0s
    1. Improving the data display
      9m 29s
    2. Passing user-selected data to a detail activity
      11m 36s
    3. Working with multiple database tables
      10m 28s
    4. Deleting data from database tables
      10m 27s
  7. 49s
    1. Where to go from here
      49s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Android SDK: Local Data Storage.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.