tags:

views:

40

answers:

2

I'm having an xml file in the below format:

<Query>
   <map>
      <value name="val1">1</value>
      <value name="val2">2</value>
   </map>
</Query>
<Quest>
   <map>
      <value name="val1">6</value>
      <value name="val2">8</value>
   </map>
</Quest>

When I write my SAX parser, I get all the values from start to end, but I need to write a condition what would take in a tag name, like Query / Quest and get only the name and value for their specific.

I'm not sure how to add this condition, I don't need to parse the rest of the tags once my condition is met and my object is parsed.

NOTE: I'm writing in Java.

+2  A: 
  • In startElement, check the element name against the given name. For example, if you are looking for "Query" and the name is "Query", set some flag to true.
  • In startElement, if the element name is "value" and the flag is true, store the name and value in a map.
  • In endElement, if the element name equals "Query", set the flag to false. Optionally, stop parsing altogether.
Sjoerd
@Sjoerd: Any idea how to skip reading a tag?
Panther24
With Sax you can't. You read the whole file until you have all the information you need.
Mark
A: 

If you only want the data for a particular set of elements then a DOM based parser especially one with XPath to get the required fields might be easier.

An xpath library is jaxen which can be used with several doms I have used JDOM

Mark
@Mark: Unfortunately I have to use only Sax Parser and no additional libraries!
Panther24