Parsing can be done using two ways:
- Using DOM Parser
- Using SAX Parser
Read XML file in Java Using SAX Parser Example
In DOM parser we have to follow simple three steps:
- Parse the XML file
- Create the java object
- Manipulate the object means we can read that object or add them to list or whatever function we want we can do
But in SAX Parser its little bit different.
SAX Parser: It’s an event based parsing it contains default handler for handling the events whenever SAX parser pareses the xml document and it finds the Start tag “<” and end tag”>” it calls corresponding handler method.
Though there are other ways also to get data from xml file e.g. using XPATH in Java which is a language like SQL and give selective data from xml file.
Sample Example of reading XML File – SAX Parser
Suppose we have this sample XML file bank.xml which contains account details of all accounts in a hypothetical bank:
1. Create the SAX parser and parse the XML file: In this step we will take one factory instance from SAXParserFactory to parse the xml file this factory instance in turns give us instance of parser using the parse() method will parse the Xml file.
2. Event Handling: when Sax Parser starts the parsing whenever it founds the start or end tag it will invoke the corresponding event handling method which is public void startElement (…) and public void end Element (...).
3. Register the events: The class extends the Default Handler class to listen for callback events and we register this handler to sax Parser to notify us for call back event.
Let see java code for all these steps. To represent data from our sample xml file we need one java domain object called Account and sample code for implementing SAX parser in Java :
Advantage of SAX parser in Java:
It is faster than DOM parser because it will not load the XML document into the memory .its an event based.
No comments:
Post a Comment