The method of DOM parsing XML file of Android development _android

Source: Internet
Author: User

The examples in this article describe the way DOM parses XML files in Android. Share to everyone for your reference, specific as follows:

Write an XML file in a assets file

<?xml version= "1.0" encoding= "UTF-8"?> 
<persons> 
 <person id= "A" > 
  <name> liming </name> 
  <age>30</age> 
 </person> 
 <person id= "A" > 
  <name> Li Xiangmei </name> 
  <age>25</age> 
 </person> 
</persons>

Second, write a DOM parsing operation in the service

Package com.example.service; 
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; 
Import Com.example.domain.Person; public class Xmldomservice {public list<person> parsexml (InputStream is) {list<person> List = new Array 
  List<person> ();
  Create Dom factory object Documentbuilderfactory factory = Documentbuilderfactory.newinstance (); 
   try {//Documentbuilder object Documentbuilder Builder = Factory.newdocumentbuilder (); 
   Get Document Object documents = Builder.parse (IS); 
   Gets the root Element root = Document.getdocumentelement () of the Document object; 
   Gets all the person node objects in the persons root node nodelist personnodes = root.getelementsbytagname ("person"); Iterate through all the person nodes for (int i = 0; i < personnodes.getlength (); i++) {person PErson = new Person (); Gets the Node object Element Personnode = (Element) personnodes.item (i) corresponding to the index according to item (index);
    The specific person node//set id attribute value Person.setid (Integer.parseint (Personnode.getattribute ("id")); 
    Gets all the byte points below the node nodelist personchildnodes = Personnode.getchildnodes (); Iterate through the byte point for the person for (int index = 0; index < personchildnodes.getlength (); index++) {//Get child nodes node nod 
     E = Personchildnodes.item (index); Determines whether node nodes are element nodes if (node.getnodetype () = = Node.element_node) {//Convert nodes to element node elements = (Elem 
      ENT) node; 
         Determines whether the element node is a name element node if ("Name". Equals (Element.getnodename ()) {Person.setname () (Element.getfirstchild ()) 
      . Getnodevalue ()); else if ("Age". Equals (Element.getnodename ())) {//Determine if the Age node person.setage (new short Element.getfirstchild ().
      NodeValue ())); 
   Add the Person object to the collection list.add (person); 
  //Close the input stream is.close (); }catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); 
 } return list;

 } 
}

Third, show actions in activity

Package com.example.lession03_xml;
Import Java.io.InputStream;
Import java.util.List;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
Import Com.example.domain.Person;
Import Com.example.service.XMLContentHandler;
Import Com.example.service.XMLDomService;
Import Android.os.Bundle;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import android.view.inputmethod.InputBinding;
Import Android.widget.Button;
Import Android.widget.Toast; public class Xmlactivityextends the activity {//Declares the component public Button btn_sax,btn_dom,btn_pull, public xmldomservice Xmldomserv
Ice
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);//Set the view displayed
Setcontentview (R.layout.activity_xml);
Xmldomservice=new Xmldomservice ();
Gets the component btn_sax= (Button) Findviewbyid (R.id.btn_sax) based on the ID;
Btn_dom= (Button) Findviewbyid (r.id.btn_dom);
Btn_pull= (Button) Findviewbyid (r.id.btn_pull); //Register Event Btn_sax.setonclicklistener for button (new Myonclicklistener ());
Btn_dom.setonclicklistener (New Myonclicklistener ());
Btn_pull.setonclicklistener (New Myonclicklistener ()); @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds the items to the action bar if it I
s present.
Getmenuinflater (). Inflate (R.menu.xml, menu);
return true; }//Anonymous class class Myonclicklistener implements onclicklistener{@Override public void OnClick (View v) {int id=v.getid (); Swit
CH (ID) {Case r.id.btn_sax:toast.maketext (xmlactivity.this, "Parse with sax", Toast.length_long). Show (); try{//sax resolved Factory objects
SAXParserFactory factory=saxparserfactory.newinstance ();
Get SAX parser SAXParser Saxparser=factory.newsaxparser ();
Create handler Object Xmlcontenthandler handlerservice=new Xmlcontenthandler ();
InputStream is=getassets (). Open ("Csdn.xml");
Direct parsing Saxparser.parse (is, handlerservice);
Gets Toast.maketext (xmlactivity.this, "----" +handlerservice, Toast.length_long) through the Handlerservice object. Show (); }catch (Exception e) {E. Printstacktrace ();
} break;
Case R.id.btn_dom:inputstream Is=null; try{//Gets the input stream object that reads the file Is=getassets (). Open ("Csdn.xml");//using DOM to parse list<person> Persons=xmldomservice.parsexml (is
);
Simple test//toast.maketext (Xmlactivity.this, "" +persons.get (0). GetName (), Toast.length_long). Show ();
Toast.maketext (Xmlactivity.this, "Parse with Dom" +persons.get (0). GetName (), Toast.length_long). Show ();
}catch (Exception e) {e.printstacktrace ();} break;
Case R.id.btn_pull:toast.maketext (xmlactivity.this, "Use pull resolution", Toast.length_long). Show ();
Break
Default:break;

 }
}
}
}

I hope this article will help you with your Android programming.

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.