Android XMl parsing magic xstream 4: parse complex xml files into objects, androidxstream
For more information about xstream, see:
Android XMl parsing magic xstream 1: parse the aa. xml file in the asset folder of the android Project
Android XMl parsing magic xstream 2: Converting objects into xml
Android XMl parsing magic xstream 3: Converting complex objects into xml
1. File preparation
Put a pre-written xml file in the asset folder of the android project directory.
File Content:
<blog> <age>30</age> <name>jhon</name> <person> <pAge>36</pAge> <pName>saliy</pName> </person></blog>
2. javaBeen
package com.android10;public class Person { String pName ; String pAge ; public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName; } public String getpAge() { return pAge; } public void setpAge(String pAge) { this.pAge = pAge; } }
package com.android10;public class Product { private String name ; private String age ; private Person person ; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; }}
3. Main Methods
Package com. android10; import java. io. IOException; import java. io. inputStream; import android. app. activity; import android. OS. bundle; import com. thoughtworks. xstream. XStream; public class MainActivity extends Activity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the data stream String fileName = "aa. xml "; // file name try {InputStream in = getResources (). getAssets (). open (fileName); XStream xstream = new XStream (); // This blog ID must be consistent with that in Xml; otherwise, an error occurs. alias ("blog", Product. class); Product product = (Product) xstream. fromXML (in); System. out. println ("sss" + product. getName () + product. getAge ();} catch (IOException e) {e. printStackTrace ();}}}
4. Running result
Product jhon30 person saliy36