Read file XML Event Iterator API


Hôm nay mình giới thiệu các bạn đến với Streaming API for XML (StaX) , nó được hổ trợ sẵn trong gói jdk củng chúng ta. Và nó giúp chúng ta việc đọc file XML một cách dể dàng.

file xml của chúng ta


<?xml version="1.0" encoding="UTF-8"?>
<config>
 <item date="10/2009">
 <id>P001</id>
 <name>Apple</name>
 <price>50</price>
 <unit>100</unit>
 </item>
 <item date="12/2010">
 <id>P002</id>
 <name>Banana</name>
 <price>20</price>
 <unit>50</unit>
 </item>
 <item date="5/2013">
 <id>P003</id>
 <name>Durian</name>
 <price>65</price>
 <unit>300</unit>
 </item>
</config>

Chúng ta viết Class ReadXmlDocument cho việc đọc file XML này


package thaihoanghai;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class ReadXmlDocument {
 static final String KEY_DATE = "date";
 static final String KEY_ITEM = "item";
 static final String KEY_ID = "id";
 static final String KEY_NAME = "name";
 static final String KEY_PRICE = "price";
 static final String KEY_UNIT = "unit";

public List<Product> readConfig(String configFile){
 List<Product> products = new ArrayList<Product>();
 try {
 // First create a new XMLInputFactory
 XMLInputFactory inputFactory = XMLInputFactory.newFactory();
 // Setup a new eventReader
 InputStream in = new FileInputStream(configFile);
 XMLEventReader eventReader = inputFactory.createXMLEventReader(in);

//read the XML document
 Product item = null;
 while(eventReader.hasNext()){
 XMLEvent event = eventReader.nextEvent();
 if(event.isStartElement()){
 StartElement startElement = event.asStartElement();
 // if we have a item element we create a new item
 if(startElement.getName().getLocalPart() == (KEY_ITEM)){
 item = new Product();
 // we read the attributes from this tag and add the date
 // attribute to our object
 @SuppressWarnings("unchecked")
 // in start element can have more attribute. So we just get attribute date in start element
 Iterator<Attribute> attributes = startElement.getAttributes();
 while(attributes.hasNext()){
 Attribute attribute = attributes.next();
 if(attribute.getName().toString().equals(KEY_DATE)){
 item.setDate(attribute.getValue());

 }
 }
 }
 if(event.isStartElement()){
 if(event.asStartElement().getName().getLocalPart().equals(KEY_ID)){
 event = eventReader.nextEvent();
 item.setId(event.asCharacters().getData());
 continue;
 }
 }
 if (event.asStartElement().getName().getLocalPart().equals(KEY_NAME)) {
 event = eventReader.nextEvent();
 item.setName(event.asCharacters().getData());
 continue;
 }

if (event.asStartElement().getName().getLocalPart().equals(KEY_PRICE)) {
 event = eventReader.nextEvent();
 item.setPrice(Double.parseDouble(event.asCharacters().getData()));
 continue;
 }

if (event.asStartElement().getName().getLocalPart().equals(KEY_UNIT)) {
 event = eventReader.nextEvent();
 item.setUnit(Integer.parseInt(event.asCharacters().getData()));
 continue;
 }
 }
 // If we reach the end of an item element we add it to list
 if(event.isEndElement()){
 EndElement endElement = event.asEndElement();
 if(endElement.getName().getLocalPart() == (KEY_ITEM)){
 products.add(item);
 }
 }
 }
 } catch (Exception e) {
 e.printStackTrace();
 }

return products;

}

}

Now , quá dể dàng, giờ chúng ta có thể test :

Class main :


package thaihoanghai;

import java.util.List;

public class TestRead {
 public static void main(String[] args) {
 ReadXmlDocument read = new ReadXmlDocument();
 List<Product> readConfig = read.readConfig("fileConfig.xml");
 for(Product item : readConfig){
 System.out.println(item);
 }
 }
}

Result …………

d1

 

Nguồn tham khảo : http://www.vogella.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: