Android parses xml files (1)

Source: Internet
Author: User

It is common for Android phones to process xml data. when data is transmitted on different platforms, we may use xml, Which is platform-independent, it is widely used in data communication. How does one Parse xml file data in android?

There are usually three methods: DOM, SAX, and PULL.

In this section, we use the DOM method for processing.

The DOM-based xml parsing method first reads all xml documents into the memory, and then uses the dom api to access the tree structure and obtain data. But what if the xml file is large? Of course, the mobile phone's CPU processing capabilities cannot be compared with PC machines, so the processing efficiency is relatively poor. Of course, this is for other methods to process xml documents.

To parse the xml document, of course, there must be an xml document file. I made a river randomly and put it in the assets Directory:

View Code

<? Xml version = "1.0" encoding = "UTF-8"?>
<Rivers>
<River name = "lingqu" length = "605">
<Introduction>
Ling Qu is located in PiXian County, Guangxi Zhuang Autonomous Region. It is one of the oldest canal in the world and has a reputation as the pearl of ancient water conservancy buildings in the world. Ling Qu, formerly known as Qin shiqu, zhiqu, douhe, and pihe, became open in 214 BC. It was still used in 2217.
</Introduction>
<Imageurl>
Http://imgsrc.baidu.com/baike/pic/item/389aa8fdb7b8322e08244d3c.jpg
</Imageurl>
</River>

<River name = "" length = "200">
<Introduction>
Starting from the Yellow Sea, lingshan Haikou, south of the Jiaolai canal, and arriving at Sanshan Island in the Bohai Sea in the north, it flows through Jiannan, Jiaozhou, Pingdu, Gaomi, Changyi, and Laizhou, with a total length of 200 kilometers and a basin area of 5400 square kilometers, china north and south run through the Shandong Peninsula to communicate with Huang Bo. The Jiaolai canal is diverted from the North-South watershed in the east of Yaojia village in Pingdu. The nanliu River is 30 kilometers long and is imported from the Mawan port to the Jiaozhou Bay. The north flow enters the Laizhou Bay from the Haicang port, which is a North Jiaozhou River with a length of more than 100 kilometers.
</Introduction>
<Imageurl>
Http://imgsrc.baidu.com/baike/pic/item/389aa8fdb7b8322e08244d3c.jpg
</Imageurl>
</River>

<River name = "North Jiangsu region general channel" length = "168">
<Introduction>
Located in the northern part of Jiangsu Province in the lower part of the Huai River, a large artificial river flows through Hongze, Qingpu, huai'an, Funing, Sheyang, Binhai, and other six counties (districts), from the east to the flat port to the sea. The total length is 168 km.
</Introduction>
<Imageurl>
Http://imgsrc.baidu.com/baike/pic/item/389aa8fdb7b8322e08244d3c.jpg
</Imageurl>
</River>
</Rivers>

So what should we do?

The specific ideas are as follows:

* First, use DocumentBuilderFactory to create a DocumentBuilderFactory instance.
* Use DocumentBuilderFactory to create DocumentBuilder.

* Then load the XML Document ),
* Then obtain the root node (Element) of the document ),
* Obtain the list (NodeList) of all child nodes in the root node ),
* Obtain the nodes to be read from the subnode list.

Of course, we observe the node. I need to use a River object to save the data and abstract the River class.

View Code

public class River implements Serializable { 
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
private int length;
private String introduction;
private String imageurl;
}

The following code reads the xml Document Object and adds it to the List:

Here we use the river. xml file in assets, so we need to read this xml file and return the input stream.

The read method is: inputStream = this. context. getResources (). getAssets (). open (fileName); the parameter is the xml file path. Of course, the default assets directory is the root directory.

Then, you can use the parse method of the DocumentBuilder object to parse the input stream, return the document object, and traverse the node attributes of the doument object.

View Code

// Obtain all river data
/**
* FileName: the path of the xml document.
*/
Public List <River> getRiversFromXml (String fileName ){
List <River> rivers = new ArrayList <River> ();
DocumentBuilderFactory factory = null;
DocumentBuilder builder = null;
Document document = null;
InputStream inputStream = null;
// First find the xml file
Factory = DocumentBuilderFactory. newInstance ();
Try {
// Locate xml and load the document
Builder = factory. newDocumentBuilder ();
InputStream = this. context. getResources (). getAssets (). open (fileName );
Document = builder. parse (inputStream );
// Find the root Element
Element root = document. getDocumentElement ();
NodeList nodes = root. getElementsByTagName (RIVER );
// Traverse all child nodes of the root node and all river nodes under rivers
River river = null;
For (int I = 0; I <nodes. getLength (); I ++ ){
River = new River ();
// Obtain the river Element Node
Element riverElement = (Element) (nodes. item (I ));
// Obtain the name attribute value in the river
River. setName (riverElement. getAttribute (NAME ));
River. setLength (Integer. parseInt (riverElement. getAttribute (LENGTH )));
// Obtain the introduction label under the river
Element introduction = (Element) riverElement. getElementsByTagName (INTRODUCTION). item (0 );
River. setIntroduction (introduction. getFirstChild (). getNodeValue ());
Element imageUrl = (Element) riverElement. getElementsByTagName (IMAGEURL). item (0 );
River. setImageurl (imageUrl. getFirstChild (). getNodeValue ());
Rivers. add (river );
}
} Catch (IOException e ){
E. printStackTrace ();
} Catch (SAXException e ){
E. printStackTrace ();
}
Catch (ParserConfigurationException e ){
E. printStackTrace ();
} Finally {
Try {
InputStream. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
Return rivers;
}

Add them to the List, and use ListView to display them. :

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.