Java XML - SPLessons

Java XML STAX Parser

Home > Lesson > Chapter 10
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java XML STAX Parser

Java XML STAX Parser

shape Introduction

Pull Parsing: Before going to Java StAX parser, one need to know what is Pull parsing. A programming model inner which a product calls methods on a xml parser while requires to have association with a xml archive is referred to as pull-parsing. Advantages of Pull Parsing:

shape Description

Stax remains for streaming api for xml which is a java spilling programming interface and is utilized to ponder and compose xml records. Stax permits to make a bidirectional xml parser this is quick, exceedingly clean to programming and has a gentle memory impact. Stax is the latest programming interface in jaxp family and offers a differentiating decision to sax and dom for developers searching for prevalent move keeping separated, taking care of and exchange, especially with low memory. A stax pull parser can channel xml measurements, for instance, that segments pointless to the client can be overlooked. In push parsing, utility needs to get all parts considering there's no separating arrangement.

Why StAX Parser?

  • StAX comes under Pull parsing category. It gives parsing control to the developer which permits to request the following event(pull the event).
  • StAX was made to address constraints in SAX and DOM.
  • Adjusting XML is effectively finished with StAX and it is bi-directional.
  • Faster than DOM as the document involved is not deeply nested.
Dis-advantages: To track the parser data a separate code has to be written and data has to be stored on your own.

StAX API Types

shape Description

There are two types of StAX API. They are:

Iterator API

Iterator programming interface parses the xml report and returns occasion things. events for detail, literary substance, comment and so on are pulled by method for the product. that is like the java iterator in accumulations. => Real interfaces incorporate xmlevent, xmleventreader and xmleventwriter. base of the iterator interface is xmlevent. nextevent() is the imperative thing strategy which gives back the consequent event in xml development which is comparative yo next in iterator arrangement. => Underneath are the occasion assortments of stax parser.

Cursor API

Cursor api is like jdbc resultset. it pushes ahead and as soon as in goes beyond a aspect, it cannot reach lower back once more. => Predominant interfaces for cursor are xmlstreamreader and xmlstreamwriter. => Cursor api is fundamentally the same as sax as it's miles uni-directional and offers a light weight reminiscence affect.

shape Example

Below is the input XML document that has to be parsed. Initially, create a XML file with the root element class, student as the child and firstname, lastname, nickname and marks as the sub-childs. [xml] <?xml version="1.0"?> <class> <student rollno="393"> <firstname>John</firstname> <lastname>Mike</lastname> <nickname>Jom</nickname> <marks>85</marks> </student> <student rollno="493"> <firstname>Rafeal</firstname> <lastname>Nadal</lastname> <nickname>Rafa</nickname> <marks>95</marks> </student> <student rollno="593"> <firstname>Samuel</firstname> <lastname>Johnson</lastname> <nickname>Sam</nickname> <marks>90</marks> </student> </class> [/xml] StAXParserDemo.java [java] package com.splessons.xml; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Iterator; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class StAXParserDemo { public static void main(String[] args) { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; try { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader eventReader = factory.createXMLEventReader( new FileReader("input.txt")); //loops over all the elements available and returns true if more parsing events else false while(eventReader.hasNext()){ XMLEvent event = eventReader.nextEvent(); //now print the element by choosing the respective method switch(event.getEventType()){ case XMLStreamConstants.START_ELEMENT: //StartElement asStartElement() - used to retrieve value and attributes of element. StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); if (qName.equalsIgnoreCase("student")) { System.out.println("Start Element : student"); Iterator<Attribute> attributes = startElement.getAttributes(); String rollNo = attributes.next().getValue(); System.out.println("Roll No : " + rollNo); } else if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } break; case XMLStreamConstants.CHARACTERS: //Characters asCharacters() - can be used to obtain characters such a CDATA, whitespace Characters characters = event.asCharacters(); if(bFirstName){ System.out.println("First Name: " + characters.getData()); bFirstName = false; } if(bLastName){ System.out.println("Last Name: " + characters.getData()); bLastName = false; } if(bNickName){ System.out.println("Nick Name: " + characters.getData()); bNickName = false; } if(bMarks){ System.out.println("Marks: " + characters.getData()); bMarks = false; } break; case XMLStreamConstants.END_ELEMENT: //EndElement asEndElement() - called at the end of a element. EndElement endElement = event.asEndElement(); if(endElement.getName().getLocalPart().equalsIgnoreCase("student")){ System.out.println("End Element : student"); System.out.println(); } break; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XMLStreamException e) { e.printStackTrace(); } } } [/java] The XMLEventReader Class give iterator of occasions which can be utilized to repeat over occasions as they happen while parsing the XML report. The XMLStreamReader Class give iterator of occasions which can be utilized to emphasize over occasions as they happen while parsing the XML report. Output : [java] Start Element : student Roll No : 393 First Name: John Last Name: Mike Nick Name: Jom Marks: 85 End Element : student Start Element : student Roll No : 493 First Name: Rafeal Last Name: Nadal Nick Name: Rafa Marks: 95 End Element : student Start Element : student Roll No : 593 First Name: Samuel Last Name: Johnson Nick Name: Sam Marks: 90 End Element : student [/java]

Summary

shape Key Points

  • StAX is a pull parser.
  • StAX allows to create a bidirectional XML parser and is fast.
  • Iterator API and Cursor API are StAX API types.