1. First we can create a raw package under the RES package path, then create a email.xml file under raw and modify its contents as follows:
1 <?XML version= "1.0" encoding= "Utf-8"?>2 <Email>3 < from>[Email protected]</ from>4 < to>[Email protected]</ to>5 <Date>2016/4/5</Date>6 <title>XML parse</title>7 <content>Hello world!</content>8 </Email>
2. use Java code to simply parse the above XML file and display the parsed information through TextView:
1 Private voidParsexml () {2 Try {3 //---Get the XML file to the input rheological amount4InputStream stream =getresources (). Openrawresource (r.raw.email);5 Stream.reset ();6 //---Start parsing xml files7Documentbuilder Builder =documentbuilderfactory.newinstance (). Newdocumentbuilder ();8Document doc =Builder.parse (stream);9Node root =doc.getfirstchild ();TenNodeList NodeList =root.getchildnodes (); OneString info = ""; A //---Loop to read information about each child node - for(inti = 0; I < nodelist.getlength (); i++) { -Node item =Nodelist.item (i); theinfo + = item.gettextcontent () + "\ n"; - } - //---Output parsing results -TextView Tvinfo =(TextView) Findviewbyid (r.id.tvinfo); + Tvinfo.settext (info); - } + Catch(Exception e) { A e.printstacktrace (); at } -}
The final effect is as follows:
These are simple parsing of XML documents, and we can add IDs and various other attributes to each node. We can pass
getElementsByTagName ();
GetAttributes ();
Getchildnodes ();
ReplaceChild (node NewChild, node Oldchild);
RemoveChild (Node oldchild);
and other methods to read and write and modify.
Parsing of the "Android" XML file