Friday, January 6, 2012

Conveniently Processing Large XML Files with Java

When processing XML data I find it most convenient to load the whole document using a DOM parser and fire some XPath-queries against the result. However, since we're building a multi-tenant eCommerce plattform we regularly have to handle large XML files, with file sizes above 1 GB. You certainly don't want to load such a beast into the heap of a production server, since it easily grows up to 3GB+ as DOM representation.

So what to do? Well, SAX to the rescue! Processing a large XML file using a SAX parser still requires constant (low) memory, since it only invokes callback for detected XML tokens. But, on the other hand, parsing complex XML really becomes a mess.

To resolve this problem we need to have a closer look at our XML input data. Most of the time, at least in our cases, you don't need the whole DOM at once. Say your importing product informations, it sufficient to look at one product at a time. Example:

        <name>Node 1</name>
        <name>Node 2</name>
        <name>Node 3</name>
            <resource type="test">Hello 1</resource>
            <resource type="test1">Hello 2</resource>

When processing Node 1, we don't need access to any attribute of Node 2 or three, respectively when processing Node 2, we don't need access to Node 1 or 3, and so on. So what we want is a partial DOM, in our example for every <node>.

What we've therefore built is a SAX parser, for which you can specify in which XML elements you are interested. Once such an element starts, we record the whole sub-tree. When this completes we notify a handler which then can run XPath expressions against this partial DOM. After that, the DOM is released and the SAX parser continues.

Here is a shortened example of how you could parse the XML above - one "<node>" at a time:

   XMLReader r = new XMLReader();

   r.addHandler("node", new NodeHandler() {

     public void process(StructuredNode node) {

   r.parse(new FileInputStream("src/examples/test.xml"));

The full example, along with the implementation is open source (MIT-License) and available here:

We successfully handle up to five parallel imports of 1GB+ XML files in our production system, without measurable heap growth. (Instead of using a FileInputStream, we use JAVAs ZIP capabilities and directly open and process ZIP versions of the XML file. This shrinks those monsters down to 20-50MB and makes uploads etc. much easier.)

This post is the first part of the my series "Enterprisy Java" - We share our hints and tricks how to overcome the obstacles when trying to build several multi tenant web applications out of a set of common modules.


  1. Nice little bit of code, thanks for sharing. Apache Jersey has similar capabilities for stream parsing JSON and building a tree of just the bits you are interested in but I've always been surprised why there isn't this type of support in a core Java XML library.

  2. Hi Andy,
    That's a nice approach indeed. I would also recommend you having a look at our approach that was specifically designed to handle very large XML input using SAX. The product allows you to specify (runtime config subscription) which types you want to process and sends these as JavaBeans to the processor component. It also allows you to specify how to handle 1..many relationships. So, for instance, say I'd like to process the element and I'd also want to process each of the elements, I could do that detaching the elements from their parent. Well, have a look hre: or here:

    Kind regards,
    Lolke Dijkstra

  3. Hi how to get the values in one Time loading.the hanlder is not working in the order.

    1. Sorry, I don't get the question. The handler behaves pretty much like a sax parser. Therefore you get all values in the order of the document

      regards Andy

  4. Not SAX, it is so 1990s, vtd-xml is the answer

    1. Nope not to this question...

      The first sentence on the website says:
      The world's most memory-efficient (1.3x~1.5x the size of an XML document) random-access XML parser.

      Having to deal with 1 GB large XML files, that still too much and the SAX/partial DOM approch is better for this purpose.

  5. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too.
    Twin Cities Web Design

  6. This comment has been removed by the author.

  7. They follow the footstep of great people, read all scriptures by heart, believe in the almighty, study and remember the latest scientific studies to find some way which can lead them to success and happiness. share more details.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

  8. I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read !! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site.

    Data Science Course

  9. It's really nice and meanful. it's really cool blog. Linking is very useful have really helped lots of people who visit blog and provide them usefull information.

    Data Science Training

  10. Thanks for your post! Through your pen I found the problem up interesting! I believe there are many other people who are interested in them just like me! Thanks your shared!..
    acte velachery reviews

    acte tambaram reviews

    acte anna nagar reviews

    acte porur reviews

    acte omr reviews

    acte chennai reviews

    acte student reviews


  11. Fantastic article I ought to say and thanks to the info. Instruction is absolutely a sticky topic. But remains one of the top issues of the time. I love your article and look forward to more.
    360DigiTMG Data Science Training Institute in Bangalore

  12. Thanks for sharing amazing article it was very useful thank you.

    Data Science Training in Hyderabad

  13. Thanks for sharing such an great blog enjoined reading it thank you.
    Data Analytics Certification Training 360DigiTMG

  14. I am impressed by the information on the blog keep up the good work.
    Data Analytics Certification Training

  15. I would Thanks for sharing this wonderful content.its very useful to us.This is incredible,I feel really happy to have seen your webpage.I gained many unknown information, the way you have clearly explained is really fantastic.keep posting like this information.
    python training in bangalore

    python training in hyderabad

    python online training

    python training

    python flask training

    python flask online training

    python training in coimbatore
    python training in chennai

    python course in chennai

    python online training in chennai

  16. Thanks for such awesome blog. Your article is very easy to understand, informative and provide complete overview about software testing. Please consider including rss feed in your website, so I get your recent post on my site.
    Salesforce Training in Chennai

    Salesforce Online Training in Chennai

    Salesforce Training in Bangalore

    Salesforce Training in Hyderabad

    Salesforce training in ameerpet

    Salesforce Training in Pune

    Salesforce Online Training

    Salesforce Training

  17. It is really a great and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us informed like this. Thank you for sharing.
    PMP Training

  18. keep up the good work. this is an Ossam post. This is to helpful, i have read here all post. i am impressed. thank you. this is our site please visit to know more information
    data science training in courses

  19. With its huge capabilities, Python is also a favorite among web developers to build various types of web applications. The web application framework, Django has been developed using Python and serves as the foundation for popular websites like 'The Guardian', 'The NY Times', 'Pinterest' and more. data science course in india

  20. Superb article and I would really like to thank for your article it’s really helpful.

    Java Training in Chennai

    Java Course in Chennai

  21. Thank you for excellent article.You made an article that is interesting.
    data science course in noida


  22. This is a really very nice post you shared, i like the post, thanks for sharing..

    Data Science Training

  23. It is amazing and wonderful to visit your site. Thanks for sharing information; this is useful to us....
    graphic design training in Delhi


  24. This piece of writing will assist the internet visitors for setting up new webpage or even a weblog from start to end
    data scientist course in hyderabad

  25. Thanks for sharing useful information. I learned something new from your bog. Its very interesting and informative. keep updating.Amazon Web Services Training in Chennai

  26. I have voiced some of the posts on your website now, and I really like your blogging style. I added it to my list of favorite blogging sites and will be back soon ...

    Data Analytics Course in Bangalore

  27. It is late to find this act. At least one should be familiar with the fact that such events exist. I agree with your blog and will come back to inspect it further in the future, so keep your performance going.

  28. Thanks for sharing your wealthy information. This is one of the excellent posts which I have seen. I go through your all of your blog, but this blog is the best one. It is really what I wanted to see hope in future you will continue for sharing such an excellent post
    thời gian bay từ los angeles về việt nam

    đặt vé máy bay từ đức về việt nam

    ve may bay tu Anh ve Viet Nam

    có chuyến bay từ úc về việt nam không

    Giá vé máy bay Vietnam Airline tu Dai Loan ve Viet Nam

    giá vé máy bay từ canada về việt nam

  29. I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic.

    Data Analytics Course in Bangalore

  30. This post is very simple to read and appreciate without leaving any details out. Great work!
    data science course aurangabad

  31. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting.
    ServiceNow Training in Chennai

  32. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.
    servicenow training and placement in hyderabad

  33. It is truly a well-researched content and excellent wording. I got so engaged in this material that I couldn't wait reading. I am impressed with your work and skill. Thanks.
    servicenow training and placement in hyderabad

  34. It's like you've got the point right, but forgot to include your readers. Maybe you should think about it from different angles.
    Data Scientist Course Syllabus

  35. Such a helpful article. Interesting to peruse this article.I might want to thank you for the endeavors you had made for composing this wonderful article.
    data science online training in hyderabad

  36. Excellent and informative blog. If you want to become data scientist, then check out the following link. Data Science Course in Hyderabad

  37. I see some amazingly important and kept up to length of your strength searching for in your on the site
    cyber security training malaysia

  38. Very informative message! There is so much information here that can help any business start a successful social media campaign!'

    Data Science Training in Kolkata

  39. What a really awesome post this is. Truly, one of the best posts I've ever witnessed to see in my whole life. Wow, just keep it up.
    data science course

  40. Wow, what great information on World Day, your exceptionally nice educational article. a debt of gratitude is owed for the position.

    Data Science Training in Erode

  41. This comment has been removed by the author.

  42. Creative Marketers BD is a team of skilled digital marketers for offering quality SEO, Content Writing and Graphics Design, and Web Development works. We are providing Digital Marketing Services both for companies and individuals.

    Are you Looking for cost effective Logo design in bangladesh? So you are the right place to start! With Creative Marketers BD, get the best responsive website design for your online business. We are here to help your business to be a success! We can expand your business through reaching to the right audience.

    To expand your business locally or globally, Creative Marketers BD is the perfect choice for you. If you want to grow your business with the help of effective digital marketing works, Creative Marketers BD is available to assist you wholeheartedly.

  43. Xilisoft Video Converter Ultimate is not difficult to change over video records utilizing Xilisoft Video Converter Ultimate Crack. The bundle incorporates video transformation programming. X Video Converter Free Download Crack

  44. Hi there, I would like to subscribe for this web
    site to take hottest updates, thus where can i do it please company registration for hyip

  45. Siblings are always there to point out our mistakes whenever we tend to step in the wrong path. Happy Sister’s Day. Happy Sister Day

  46. Our Data Science certification training with a unique curriculum and methodology helps you to get placed in top-notch companies. Avail all the benefits and become a champion.
    data science courses in malaysia

  47. Macrium Reflect Crack is a software application designed for Windows operating system that provides backup, imaging, and cloning capabilities for individual computers or servers. The software allows users to create full or partial backups of their hard drives, including all data, operating systems, and applications, and store them on an external storage device or network location.

  48. Nero Burning Crack
    Nero Burning Crack is the world’s best burning engine. Duplicate and copy excellent Albums, DVDs, and Blu-beam Plates.

  49. Nice blog! Thanks for sharing this valuable information. Discover the ultimate learning experience for your 7th standard student with Ziyyara Edutech's private online tuition classes.
    Book A Free Demo Today visit Home tuitions for 7th standard

  50. Excellent post and I am very happy to read this blog. Keep doing...! Ziyyara Edutech online tuition for Class 11 provides comprehensive guidance and in-depth explanations to help you excel in your physics curriculum.
    For more info Contact us: +91-9654271931, +971-505593798 or visit Online tuition for class 11

  51. If you are a student looking for extra help in Class 11 Physics, I recommend checking out the online tuition offered by Ziyyara Edutech. Their experienced instructors provide clear explanations of physics concepts and problem-solving approaches. Lessons are tailored to align with the key learning objectives and exam pattern. Ziyyara Edutech uses interactive teaching methods like simulations, videos and quizzes to engage students. You can schedule convenient online classes from the comfort of your home. Their 1-on-1 tutoring provides personalized attention and feedback. With Ziyyara Edutech's Class 11 Physics tuition, you can gain the knowledge and skills to excel in this crucial subject. Their structured curriculum and expert guidance can help boost your academic performance. I encourage you to explore their physics tutoring programs if you need quality support and learning resources.Bigg Boss Malayalam

  52. Thanks for sharing such an informative and useful blog with us.
    Java training in Pune