Java XML - SPLessons

Java XML Streaming API

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

Java XML Streaming API

Streaming API for XML

shape Description

Here first the user need to know about Pull Parsing and Push Parsing. Streaming pull parsing alludesto a programming version wherein a consumer application calls strategies on an xml parsing library whilst it wishes to cooperate with an xml infoset; this is, the consumer just receives (pulls) xml information while it unequivocally requests it. streaming push parsing insinuates a programming form wherein a xml parser sends (pushes) xml certainties to the customer in light of the fact that the parser encounters added substances in a xml infoset; this is, the parser sends the actualities regardless of whether the customer is set up to use it around then.

Java StAX Parser

shape Description

The Streaming API for XML (StAX), determined by JSR-173 of Java Community Process, gives a simple and instinctive method for parsing and producing XML reports and is like the SAX API, yet empowers a procedural, stream-based treatment of XML archives as opposed to the obliging developer to compose SAX event handlers, which can get convoluted when you work with complex XML records. StAX gives you more control over parsing than the SAX. The following are the advantages of StAX.

DOM versus Streaming

shape Description

DOM is platform browser and language neutral. It does not assume anything about what platform is running on what browser turning on and there are several language implementations of the DOM that can be used to work with. One of the maximum commonplace languages that human beings work with the dom is javascript. The usage of xml dom the consumer can add, edit, cast off or pass nodes in the tree at any point with a view to create an software. Following is the stax parser photograph. Streaming alludes to a programming version in which xml infosets are transmitted and parsed serially at software runtime, frequently step by step, and regularly from detail assets whose substance are not effectively known earlier. In addition, stream-primarily based parsers can start creating yield directly, and infoset additives may be disposed of and garbage amassed immediately after they're utilized. While giving a littler memory affect, reduced processor stipulations, and better execution in unique circumstances, the essential exchange off with movement handling is that developer can simply look at the infoset kingdom at one region without delay in the archive.

Push Parsing versus Pull Parsing

shape Description

Streaming push parsing insinuates a programming adaptation in which a xml parser sends (pushes) xml certainties to the customer on the grounds that the parser audits added substances in a xml infoset—that is, the parser sends the information paying little mind to regardless of whether the benefactor is set up to make utilization of it around then. Streaming pull parsing suggests a programming rendition wherein a customer programming calls methodologies on a xml parsing library while it wishes to connect with a xml infoset—this is, the buyer essentially gets (pulls) xml measurements while it unequivocally asks for it. Pull parsing libraries are more diminutive and the supporter code to converse with those libraries an incredible arrangement a great deal less troublesome than with push libraries, despite for more contemplation's boggling audits.

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 equalsIgnoreCase() strategy looks at this String to another String, disregarding case contemplations. Two strings are viewed as equivalent overlooking case, on the off chance that they are of a similar length, and comparing characters in the two strings are equivalent disregarding case. The class javax.xml.stream.XMLInputFactory is a root part of the Java StAX API. From this class you can make both a XMLStreamReader and a XMLEventReader. 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 : Now compile the code result will be as follows. [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

  • Streaming API for XML - 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.