• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Simple XML Parsing

 
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Lets say I have an XML file of the format


If I parse the above with a SAXParser and override DefaultHandlers startElement and endElement methods, how do I differentiate between the 2 'nSamples' tokens from each other. What would be an alternate parsing technique that would give me the nested level info of each tag?
 
Marshal
Posts: 28260
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You don't need an alternate parsing method. One idea would be to have your startElement method push the element name onto a stack and have the endElement method pop it from the stack. Then to answer that particular question you could just look at the size of the stack. To answer other possible questions (like what's the name of nSamples's parent) you could look at the contents of the stack. And so on.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Other, slightly "more OO" solutions:

- exchange the handler when you hit the item start tag. The new handler could reset to the old one when it hits the item end tag.

- use the Strategy pattern for handling the nSamples tag. Change the strategy when you hit the item start or end tag.

Which one is better depends on the specifics of your requirements.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moving to our XML forum...
 
reply
    Bookmark Topic Watch Topic
  • New Topic