• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Searching with SAX in xml

 
Sebastian Green
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to search an xml-file using the SAX-parser. Like, show all nodes where the personid-node equals 001. Im having a hard time understanding XML and SAX in generall. Can anyone help me, point me in tha right direction? I have tried to use the ranchs wiki faq tutorial. But it didnt help so much...
 
Hari Vignesh Padmanaban
Ranch Hand
Posts: 578
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look at this
http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/sax/index.html
hope this helps
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It might be a lot easier to start with DOM instead of SAX.
With DOM, you get an object tree which you can iterate with for loops etc. and pick the nodes that match into, say, an ArrayList.
 
Sebastian Green
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps I should start with the DOM but the task rquiers using SAX. And the Sun-Tutorial is very long, Im looking for something shorter. I found something at the The Java Developers Almanac (http://www.javaalmanac.com/egs/javax.xml.parsers/BasicSax.html) but its only parse the xml-file. I want to the parser to print out every childnode to every node called <person>.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even better, use of XPath (as in XSLT) would be better (with Xalan for instance).
The XPath expression for returning all the person whose id nodes equals to 1 would look something like:

For instance, in the following xml document there are a number of person nodes:

The following code will display the person with id 001:

Cheers
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sebastian,
If you'd like to use Sax events, it's another story as no document tree is available.
Given the same xml file as before, the following code uses Sax to render the found person:

Of course this code is incomplete and just fits the simple example, but that should give you an idea of what to do to get the job done.
Cheers
 
Sebastian Green
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your tips I will check them out right away (have been busy for a while). Im aware of the XPath, Im getting to soon but I need to understand the basic first. The next task will be XPath related. Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic