Android XML parsing Magic XStream VI: Transforming a collection list into an XML document

Source: Internet
Author: User

Preface: For XStream do not understand, please see:

Android XMl parsing Magic XStream: Parse aa.xml file under Asset folder in Android project

Android XML parsing Magic XStream II: Converting objects to XML

Android XML parsing Magic XStream Three: Transforming complex objects into XML

Android XML parsing Magic XStream Four: parsing complex XMl files into objects

Android XML parsing Magic XStream Five: Transforming complex objects into XML and writing XML files to SD cards

1. Create Javabeen

 PackageCom.android10; Public classPerson {String pName;        String PAge;  PublicString Getpname () {returnPName; }     Public voidsetpname (String pName) { This. PName =PName; }     PublicString GetPage () {returnPAge; }     Public voidsetpage (String pAge) { This. PAge =PAge; } }

 PackageCom.android10; Public classProduct {PrivateString name; PrivateString age; Privateperson person ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getage () {returnAge ; }     Public voidsetage (String age) { This. Age =Age ; }     PublicPerson Getperson () {returnPerson ; }     Public voidSetperson (person person) { This. person =Person ; }}

  COM.ANDROID10;  import   java.util.List;  public  class   Listbean {  root;  public  list<product> Getroot () {    /span>return   root;  public  void  setroot (list< Product> this . Root = root; }}


2. Main methods

 PackageCom.android10;ImportJava.io.ByteArrayInputStream;ImportJava.io.ByteArrayOutputStream;Importjava.util.ArrayList;Importjava.util.List;ImportJavax.xml.transform.OutputKeys;ImportJavax.xml.transform.Source;ImportJavax.xml.transform.Transformer;ImportJavax.xml.transform.sax.SAXSource;Importjavax.xml.transform.sax.SAXTransformerFactory;ImportJavax.xml.transform.stream.StreamResult;ImportOrg.xml.sax.InputSource;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportCom.thoughtworks.xstream.XStream; Public classMainactivityextendsActivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); XStream XStream=NewXStream (); List<Product> root =getList (); //sets an empty element in the collection in Listbean, that is, the collection element label is not displayedXstream.addimplicitcollection (Listbean.class, "Root"); Xstream.autodetectannotations (true); //Setting AliasesXstream.alias ("Product", product.class ); //set name to the property of the element of the parent class (Student)Xstream.useattributefor (Product.class, "name" ); //Convert list collection to XML stringString xmlstring =Xstream.toxml (root); //writes an XML string to an SD card XML fileXstreamutil Xstreamutil =NewXstreamutil (); Xstreamutil.writetoxml ( This, xmlstring); //Convert an XML string into a list collectionlist<product> list =NewArraylist<product>() ; List= (list<product>) Xstream.fromxml (xmlstring); System.out.println ("SSS" +Formatxml (xmlstring)); }    /*** Get Data *@return     */    PrivateList<product>getList () {person Person1=NewPerson (); Person1.setpname ("Saliy" ) ; Person1.setpage ("36" ); Product Product1=NewProduct (); Product1.setname ("Jhon" ) ; Product1.setage ("30" );        Product1.setperson (Person1); Person Person2=NewPerson (); Person2.setpname ("Saliy02" ) ; Person2.setpage ("3602" ); Product Product2=NewProduct (); Product2.setname ("Jhon02" ) ; Product2.setage ("3002" );        Product2.setperson (Person2); List<Product> root =NewArraylist<product>() ;        Root.add (PRODUCT1);        Root.add (PRODUCT2); returnRoot; }    /*** Format XML string *@paramXML *@return     */     Public Staticstring Formatxml (String xml) {Try{Transformer Serializer=saxtransformerfactory.newinstance (). Newtransformer (); Serializer.setoutputproperty (Outputkeys.indent,"Yes"); Serializer.setoutputproperty ("{Http://xml.apache.org/xslt}indent-amount", "2"); Source Xmlsource=NewSAXSource (NewInputSource (NewBytearrayinputstream (Xml.getbytes ())); Streamresult Res=NewStreamresult (NewBytearrayoutputstream ());            Serializer.transform (Xmlsource, RES); return NewString ((bytearrayoutputstream) Res.getoutputstream ()). Tobytearray ()); }Catch(Exception e) {returnXML; }    }}

 PackageCom.android10;ImportJava.io.File;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.OutputStreamWriter;ImportAndroid.content.Context;Importandroid.os.Environment; Public classXstreamutil {xcallback xcallback; /*** Write XML string to SD card file *@paramContext *@paramstr XML string*/     Public voidWritetoxml (context context, String str) {//Get file pathString Sdpath = environment.getexternalstoragedirectory () + "/myfile1.xml/" ; //Create a fileFile File =NewFile (Sdpath); if( !file.exists ()) {            Try{file.createnewfile (); } Catch(IOException e) {e.printstacktrace (); }         }        //Write Data        Try{FileOutputStream out=Newfileoutputstream (file); OutputStreamWriter OUTW=NewOutputStreamWriter (out); Try{outw.write (str);                  Outw.close ();                  Out.close (); if(Xcallback! =NULL) {xcallback.success (); }            } Catch(IOException e) {if(Xcallback! =NULL) {xcallback.fail (); }            }          } Catch(FileNotFoundException E1) {e1.printstacktrace (); if(Xcallback! =NULL) {xcallback.fail (); }        }    }     //Setting up Listeners    voidSetxstreamlister (Xcallback xcallback) { This. Xcallback =Xcallback; }}Interfacexcallback{/*** Write Success*/    voidsuccess (); /*** Write Failed*/    voidfail (); }

3. Operation Result

<list>
<product name= "Jhon" >
<age>30</age>
<person>
<pAge>36</pAge>
<pName>saliy</pName>
</person>
</product>
<product name= "Jhon02" >
<age>3002</age>
<person>
<pAge>3602</pAge>
<pName>saliy02</pName>
</person>
</product>
</list>

Android XML parsing Magic XStream VI: Transforming a collection list into an XML document

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.