• No results found

Parser Example.docx

N/A
N/A
Protected

Academic year: 2020

Share "Parser Example.docx"

Copied!
6
0
0

Loading.... (view fulltext now)

Full text

(1)

How to Parse or Read XML File in Java

JAXP - Java API for XML Parsing

Java provides extensive support for reading XML file, writing XML file and accessing any element from XML file. All XML parsing related classes and methods are inside JAXP. Though DOM

related code comes from org.w3c.dom package. All XML parsers are in javax.xml.parsers package. We will see example of parsing xml files using JAXP API in next section.

Parse XML File in Java using DOM Parser

DOM is quick and easy way to parse xml files in Java and if you are doing it for testing its way

to go. Only thing to concern is that XML files which need to be parsed must not be too large.

You can also 

create xml file by using DOM parser

 and DocumentFactory Class in Java.

XML file for parsing in Java

Here is xml file Stocks.xml which contains some stocks and there price, quantity we will use this in our xml parsing example in Java.

<?xml version="1.0" encoding="UTF-8"?>

<stocks> <stock>

<symbol>Citibank</symbol> <price>100</price>

<quantity>1000</quantity> </stock>

<stock>

<symbol>Axis bank</symbol> <price>90</price>

<quantity>2000</quantity> </stock>

</stocks>

Example of Parsing XML File in Java using DOM Parser

Here is a code example of parsing above xml file in Java using DOM parser:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

public class DOMExampleJava {

public static void main(String args[]) {

(2)

File stocks = new File("Stocks.xml");

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

Document doc = dBuilder.parse(stocks); doc.getDocumentElement().normalize();

System.out.println("root of xml file" + doc.getDocumentElement().getNodeName()); NodeList nodes = doc.getElementsByTagName("stock");

System.out.println("==========================");

for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node;

System.out.println("Stock Symbol: " + getValue("symbol", element)); System.out.println("Stock Price: " + getValue("price", element)); System.out.println("Stock Quantity: " + getValue("quantity", element)); }

}

} catch (Exception ex) { ex.printStackTrace(); }

}

private static String getValue(String tag, Element element) {

NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes(); Node node = (Node) nodes.item(0);

return node.getNodeValue(); }

}

Output:

root of xml file stocks ========================== Stock Symbol: Citibank Stock Price: 100 Stock Quantity: 1000 Stock Symbol: Axis bank Stock Price: 90

(3)

To Read XML file in Java Using SAX Parser

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.

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:

<?

xml

version

="1.0"

encoding

="UTF-8"?>

<

Bank

>

<

Account

type

="saving">

<

Id

>1001</

Id

>

<

Name

>Jack Robinson</

Name

>

<

Amt

>10000</

Amt

>

</

Account

>

<

Account

type

="current">

<

Id

>1002</

Id

>

<

Name

>Sony Corporation</

Name

>

<

Amt

>1000000</

Amt

>

</

Account

>

</

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:

package parser;

public class Account {

(4)

public Account() { }

public Account(String name, int id, int amt, String type) { this.name = name;

this.amt = amt; this.id = id; this.type = type; }

public int getAmt() { return amt; }

public void setAmt(int amt) { this.amt = amt;

}

public int getId() { return id; }

public void setId(int id) { this.id = id;

}

public String getName() { return name; }

public void setName(String name) { this.name = name;

}

public String getType() { return type; }

public void setType(String type) { this.type = type;

}

public String toString() {

StringBuffer sb = new StringBuffer(); sb.append("Account Details - "); sb.append("Name:" + getName()); sb.append(", ");

sb.append("Type:" + getType()); sb.append(", ");

sb.append("Id:" + getId()); sb.append(", ");

sb.append("Age:" + getAmt()); sb.append(".");

return sb.toString(); }

(5)

Sample Code for implementing SAX parser in Java

package parser;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFileUsingSaxparser extends DefaultHandler {

private Account acct; private String temp;

private ArrayList<Account> accList = new ArrayList<Account>();

/** The main method sets things up for parsing */

public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {

//Create a "parser factory" for creating SAX parsers

SAXParserFactory spfac = SAXParserFactory.newInstance();

//Now use the parser factory to create a SAXParser object

SAXParser sp = spfac.newSAXParser();

//Create an instance of this class; it defines all the handler methods

ReadXMLFileUsingSaxparser handler = new ReadXMLFileUsingSaxparser();

//Finally, tell the parser to parse the input and notify the handler

sp.parse("bank.xml", handler);

handler.readList();

}

/*

* When the parser encounters plain text (not XML elements), * it calls(this method, which accumulates them in a string buffer */

public void characters(char[] buffer, int start, int length) { temp = new String(buffer, start, length);

} /*

* Every time the parser encounters the beginning of a new element, * it calls this method, which resets the string buffer

*/

public void startElement(String uri, String localName,

String qName, Attributes attributes) throws SAXException { temp = "";

if (qName.equalsIgnoreCase("Account")) { acct = new Account();

(6)

} }

/*

* When the parser encounters the end of an element, it calls this method */

public void endElement(String uri, String localName, String qName) throws SAXException {

if (qName.equalsIgnoreCase("Account")) { // add it to the list

accList.add(acct);

} else if (qName.equalsIgnoreCase("Name")) { acct.setName(temp);

} else if (qName.equalsIgnoreCase("Id")) { acct.setId(Integer.parseInt(temp)); } else if (qName.equalsIgnoreCase("Amt")) { acct.setAmt(Integer.parseInt(temp)); }

}

private void readList() {

System.out.println("No of the accounts in bank '" + accList.size() + "'.");

Iterator<Account> it = accList.iterator(); while (it.hasNext()) {

System.out.println(it.next().toString()); }

} }

Output:

No of the accounts in bank '2'.

Account Details - Name:Jack Robinson, Type:saving, Id:1001, Age:10000. Account Details - Name:Sony Corporation, Type:current, Id:1002, Age:1000000.

Advantage of SAX parser in Java:

References

Related documents

Any other elements to generate a different purposes specified for xml parser method name provide java sax parser example for xml document into pojo class.. SAX xml parser in

at least our data indicate that the center of the species range is much farther north than previously anticipated. longispina, which is only found in Europe, D. umbra occurs in

Participant’s rights, obligations and risks are reflected in NSCC’s Rules and include, but are not limited to: (i) initial and ongoing membership requirements, (ii) NSCC’s ability

The system will be operated under dual-license model, which means that anyone involved in OSIA open source community can use and develop the software freely under open source

The observed activity indicated that OA extract could serve as a source of potential adjuvant of antibiotic or modulation of bacterial resistance mechanism

Compared to the traditional nurse scheduling literature, our non-cyclic approach is also characterized by the flexible setting of problem parameters such as nurses’ and

– Installation program that can selectively install all components (Management Server software, Video Recording Manager software, Configuration.. Client software, Operator

The only interesting estimates for policy analysis are those conditioned on the certainty levels giving the lower and the higher bound for mean and median WTP (i.e. “definitely