Android [intermediate tutorial] Chapter 7 Dom Parser for XML Parsing

Source: Internet
Author: User

 

Next, we will introduce Dom parsing in this chapter, Because Dom is a lot of parser used in J2EE. The parsing method here is the same as that of J2EE, the specific style is the same as the style in the following article.

 

 

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

<Persons>

<Person id = "1">

<Status> big brother </status>

<Name> Sun Wukong </name>

<Tool> golden hoop </tool>

<Number> killed 50 monsters </number>

</Person>

<Person id = "2">

<Status> Second Brother </status>

<Name> pig Bajie </name>

<Tool> nine-tooth dingtalk </tool>

<Number> killed 40 monsters </number>

</Person>

<Person id = "3">

<Status> three younger siblings </status>

<Name> Sha monk </name>

<Tool> demon master pin </tool>

<Number> killed 30 monsters </number>

</Person>

 

</Persons>

For other data or styles, see the following tutorial.

Android [intermediate tutorial] Chapter 5 PULL Parser for XML Parsing

Let's look at the code at the resolution:

 

 

Import java. io. InputStream;

Import java. util. ArrayList;

Import java. util. List;

 

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 DomHandler

{

Private InputStream input;

Private List <Person> persons;

Private Person person;

Public DomHandler ()

{

}

Public DomHandler (InputStream input)

{

This. input = input;

}

 

Public void setInput (InputStream input)

{

This. input = input;

}

Public List <Person> getPersons (){

Persons = new ArrayList <Person> ();

Try

{

// Create a Dom parser using the Dom factory Method

DocumentBuilder builder = DocumentBuilderFactory. newInstance (). newDocumentBuilder ();

Document document = builder. parse (input );

Element element = document. getDocumentElement ();

// Obtain the node list of the node <person>

NodeList personNodes = element. getElementsByTagName ("person ");

// Node length

Int length = personNodes. getLength ();

For (int I = 0; I <length; I ++ ){

// Obtain the <person> node Element

Element personElement = (Element) personNodes. item (I );

Person = new Person ();

// Obtain the id attribute value in <person id = "1">

Person. setId (personElement. getAttribute ("id "));

// Continue down to obtain the subnode list, such as <status> <name>

NodeList childnodes = personElement. getChildNodes ();

Int len = childnodes. getLength ();

For (int j = 0; j <len; j ++ ){

// If the child node is an element node

If (childnodes. item (j). getNodeType () = Node. ELEMENT_NODE ){

// Obtain the node name

String nodeName = childnodes. item (j). getNodeName ();

// Obtain the node Value

String nodeValue = childnodes. item (j). getFirstChild (). getNodeValue ();

If ("status". equals (nodeName )){

Person. setStatus (nodeValue );

}

If ("name". equals (nodeName )){

Person. setName (nodeValue );

}

If ("tool". equals (nodeName )){

Person. setTool (nodeValue );

}

If ("number". equals (nodeName )){

Person. setNumber (nodeValue );

}

}

} // End for j

Persons. add (person );

} // End for I

Return persons;

 

} Catch (Exception e)

{

E. printStackTrace ();

}

Return null;

}

}

Then the code of the Activity is:

 

 

Import java. io. File;

Import java. io. FileInputStream;

Import java. util. ArrayList;

Import java. util. HashMap;

Import java. util. List;

Import java. util. Map;

 

Import android. app. Activity;

Import android. OS. Bundle;

Import android. OS. Environment;

Import android. widget. ListView;

Import android. widget. SimpleAdapter;

 

Public class PullActivity extends Activity

{

Private ListView listView;

Private SimpleAdapter adapter;

 

@ Override

Protected void onCreate (Bundle savedInstanceState)

{

// TODO Auto-generated method stub

Super. onCreate (savedInstanceState );

SetContentView (R. layout. xml_handler );

ListView = (ListView) findViewById (R. id. xml_list );

Try

{

// Adaptive Method

GetAdapter ();

} Catch (Exception e)

{

E. printStackTrace ();

}

ListView. setAdapter (adapter );

}

 

// Custom adaptation method

Private void getAdapter () throws Exception

{

List <Map <String, String> lists = new ArrayList <Map <String, String> ();

// This part is used for testing.

File SD_Files = Environment. getExternalStorageDirectory ();

String file_path = SD_Files.getName () + File. separator + "persons. xml ";

// PULL parsing document

// FileInputStream input = new FileInputStream (new File (file_path ));

// PullHandler pullHandler = new PullHandler (input );

// List <Person> persons = pullHandler. getPersons ();

// SAX parsing document

// FileInputStream FCM = new FileInputStream (new File (file_path ));

// SAXParser parser = SAXParserFactory. newInstance (). newSAXParser ();

// SaxHandler saxHandler = new SaxHandler ();

// Parser. parse (FCM, saxHandler );

// List <Person> persons = saxHandler. getPersons ();

// Dom parsing document

FileInputStream FCM = new FileInputStream (new File (file_path ));

DomHandler domHandler = new DomHandler (SOx );

List <Person> persons = domHandler. getPersons ();

// Convert the data in persons to ArrayList <Map <String, String>, because SimpleAdapter uses this type of data for adaptation.

Map <String, String> map;

For (Person p: persons ){

Map = new HashMap <String, String> ();

Map. put ("id", p. getId ());

Map. put ("status", p. getStatus ());

Map. put ("name", p. getName ());

Map. put ("tool", p. getTool ());

Map. put ("number", p. getNumber ());

Lists. add (map );

}

// Key in HashMap <String, String>

String [] from = {"id", "status", "name", "tool", "number "};

// Control ID in list_item.xml

Int [] to = {R. id. item_id, R. id. item_status, R. id. item_name, R. id. item_tool, R. id. item_number };

Adapter = new SimpleAdapter (this, lists, R. layout. handler_list_item, from, );

}

}

 

In fact, Dom is rarely used in Android, mainly considering performance issues. After all, mobile phones are no better than servers or computers.

In the next chapter, we will introduce the Json parsing method. I hope you will learn it carefully.

 

 

Haha, the long holiday in October will soon end, and I have to work hard and learn again. Thank you.

 

From: kangkangz4 Column

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.