Using XStream, for transformations between Java object and XML

Source: Internet
Author: User
Tags stub

Because is the test, therefore is first reads an XML file from the SD card, transforms the object, then takes this object to generate the XML file, writes the SD card, (if obtains from the server, can directly use returns the string)

The other thing to be aware of is coding,

The test XML file is sent first.

/sdcard/ceshi2.xml

<?xml version= "1.0" encoding= "Utf-8"?> <LETTERINFOLIST> <ROWS> <APPEALBASE> <id>20120 726131235</id> <USER_ID>2012072400010</USER_ID> <appeal_num>2012072600007</appeal_num > <APPEAL_RANDOM>7825</APPEAL_RANDOM> <CPTYPE>1</CPTYPE> <CPNAME> XXX company </cpname > <APPEAL_THEME> Letter Subject Test </APPEAL_THEME> <APPEAL_CONTONT> letter content, test </APPEAL_CONTONT> <app Eal_trans_state>9</appeal_trans_state> <APPEAL_EXTRA> Annex 1, annex 2, annex 3</appeal_extra> <appeal_
		Feedback_info>test1</appeal_feedback_info> <ANNET_WHEN_ENDCASE>test2</ANNET_WHEN_ENDCASE> </APPEALBASE> <APPEALBASE> <ID>20120726132134</ID> <user_id>2012072400010</user_ id> <APPEAL_NUM>2012072600008</APPEAL_NUM> <APPEAL_RANDOM>4453</APPEAL_RANDOM> &LT;CPT Ype>1</cptype> &LT;CPNAME&Gt; xxx </CPNAME> <APPEAL_THEME> letter subject Test </APPEAL_THEME> <APPEAL_CONTONT> letter content, test </appeal_ Contont> <APPEAL_TRANS_STATE>9</APPEAL_TRANS_STATE> <APPEAL_EXTRA> Annex 1, annex 2, annex 3</appeal_ Extra> <APPEAL_FEEDBACK_INFO>test3</APPEAL_FEEDBACK_INFO> <annet_when_endcase>test4</

 annet_when_endcase> </APPEALBASE> </ROWS> </LETTERINFOLIST>

Here are the corresponding objects


Package Com.zeng.xstream.model;

Import Com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias ("letterinfolist") public
class Letterinfolist {
	
	
	@XStreamAlias ("ROWS")
	private rows rows;

	Public Rows GetRows () {return
		rows;
	}

	public void setrows (rows rows) {
		this.rows = rows;
	}

}


Rows.java

Package Com.zeng.xstream.model;

Import java.util.ArrayList;
Import java.util.List;

Import Com.thoughtworks.xstream.annotations.XStreamAlias;
Import com.thoughtworks.xstream.annotations.XStreamImplicit;
Import com.thoughtworks.xstream.annotations.XStreamImplicitCollection;

@XStreamAlias ("ROWS")
@XStreamImplicitCollection ("letters") public
class ROWS {
	
	@XStreamAlias (" Appealbase ")
	private list<letteritem> letters;

	Public list<letteritem> Getletters () {return
		letters;
	}

	public void Setletters (list<letteritem> letters) {
		this.letters = letters;
	}

}

Letteritem.java

Package Com.zeng.xstream.model;
Import Com.thoughtworks.xstream.annotations.XStreamAlias;

Import com.thoughtworks.xstream.annotations.XStreamImplicitCollection;
	@XStreamAlias ("Appealbase") public class Letteritem {@XStreamAlias ("ID") private String ID;
	Private String user_id;
	Private String Appeal_num;
	Private String Appeal_random;
	Private String Cptype;
	Private String CPName;
	Private String Appeal_theme;
	Private String Appeal_contont;
	Private String appeal_trans_state;
	Private String Appeal_feedback_info;
	Private String Appeal_extra;

	Private String annet_when_endcase;
	Public String GetID () {return ID;
	public void SetID (String ID) {id = ID;
	Public String getuser_id () {return user_id;
	} public void setuser_id (String user_id) {user_id = user_id;
	Public String Getappeal_num () {return appeal_num;
	} public void Setappeal_num (String appeal_num) {appeal_num = Appeal_num;
	Public String Getappeal_random () {return appeal_random; }

	public void Setappeal_random (String appeal_random) {appeal_random = Appeal_random;
	Public String Getcptype () {return cptype;
	} public void Setcptype (String cptype) {cptype = Cptype;
	Public String Getcpname () {return cpname;
	} public void Setcpname (String cpname) {cpname = CPName;
	Public String Getappeal_theme () {return appeal_theme;
	} public void Setappeal_theme (String appeal_theme) {appeal_theme = Appeal_theme;
	Public String Getappeal_contont () {return appeal_contont;
	} public void Setappeal_contont (String appeal_contont) {appeal_contont = Appeal_contont;
	Public String Getappeal_trans_state () {return appeal_trans_state;
	} public void Setappeal_trans_state (String appeal_trans_state) {appeal_trans_state = appeal_trans_state;
	Public String Getappeal_feedback_info () {return appeal_feedback_info; } public void Setappeal_feedback_info (String appeal_feedback_info) {appeal_feedback_info = Appeal_feedback_info;
	Public String Getappeal_extra () {return appeal_extra;
	} public void Setappeal_extra (String appeal_extra) {Appeal_extra = Appeal_extra;
	Public String Getannet_when_endcase () {return annet_when_endcase;
	} public void Setannet_when_endcase (String annet_when_endcase) {annet_when_endcase = Annet_when_endcase;
 }

}


The above code is basically these two sentences

@XStreamAlias ("ROWS")     //Label
@XStreamImplicitCollection ("letters")//This represents an implicit array, and the value of "" is the same as the variable name you have defined.


Here is the implementation code

Xstreamutil.java

Package com.zeng.xstream;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import Com.thoughtworks.xstream.XStream;

Import Com.thoughtworks.xstream.io.xml.DomDriver;
	public class Xstreamutil {private static map<class, class> mclasses = new Hashmap<class, class> ();
	private static XStream XStream = new XStream (new Domdriver ());

	private static map<string, class> wclasses = new hashmap<string, class> ();
	 /** * * * @param CLSZ * Each layer of the label corresponding to the class (note! Not every label!)
	 * @param filename * file path ("/sdcard/test.xml") * @param NULL * temporarily useless; * @return Returns the outermost object: */public static object Xml2object (list<class> clsz, String fileName, String NULL) {for
			Class cls:clsz) {if (Mclasses.containskey (CLS)) continue;
			Mclasses.put (CLS, CLS);
		Xstream.processannotations (CLS); try {//This is set encoding, because the encoding may be different will appear garbled, this should not specifically solve the garbled problem bufferedreader br = new BufferedReader (New Inputstreamreade
			R (New FileInputStream (FileName), "GBK"));
			return Xstream.fromxml (BR); Return Xstream.fromxml (New FileReader (FileName));//This is direct read} catch (FileNotFoundException e) {//T
		Odo auto-generated catch block E.printstacktrace ();
		catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();
	return null; }/** * * @param CLSZ *: Each layer of the label corresponding to the class * @param str *: XML parsed String * @return return Back is the outermost object: */public static object Xml2object (list<class> clsz, String str) {for (Class cls:clsz) {if (MC
			Lasses.containskey (CLS)) continue;
			Mclasses.put (CLS, CLS);
		Xstream.processannotations (CLS);
	return Xstream.fromxml (str); }
	/*-The difference between the-------------------------------------------* * * Xml2object and Object2xml is the xstream.processannotations (CLS);
	 * Xstream.alias (Cls.node, CLS.CLS); * * * *-------------------------------------------* * * * * * * * * @param CLSZ */** * This is different from the above, which requires tags and typ E (Class);
	 So the definition of a class, convenient point; * @param obj * This is the Read object * @return/public static String Object2xml (list<xstreamnode> clsz, Obje
			CT obj) {for (Xstreamnode cls:clsz) {if (Wclasses.containskey (Cls.node)) continue;
			Wclasses.put (Cls.node, CLS.CLS);
		Xstream.alias (Cls.node, CLS.CLS);

	return Xstream.toxml (obj);
			Static class Xstreamnode {public Xstreamnode (String node, class CLS) {//TODO auto-generated constructor stub
			This.node = node;
		This.cls = CLS;
		Public String node;
	Public Class CLS;
 }
}

Xstreamtestactivity.java

Package com.zeng.xstream;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.util.ArrayList;

Import java.util.List;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.TextView;

Import Android.widget.Toast;
Import Com.zeng.xstream.XStreamUtil.XStreamNode;
Import com.zeng.xstream.model.LetterInfoList;
Import Com.zeng.xstream.model.LetterItem;

Import Com.zeng.xstream.model.Rows;
	public class Xstreamtestactivity extends activity {Private Button read, write;
	Private list<class> List;
	Private letterinfolist data;

	Private TextView tv_show; /** called the activity is a.
		* * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
		Setcontentview (R.layout.main);
		Read = (Button) Findviewbyid (R.id.read); Write = (BuTton) Findviewbyid (r.id.write);
		Tv_show = (TextView) Findviewbyid (r.id.show);
		List = new arraylist<class> ();
		List.add (Letterinfolist.class);
		List.add (Rows.class);
		List.add (Letteritem.class); Read.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//TODO auto-generated
				Method stub Object obj = Xstreamutil.xml2object (list, "/sdcard/ceshi2.xml", "");
				System.out.println (Obj.tostring ());
				data = (letterinfolist) obj;
			Toast.maketext (Xstreamtestactivity.this, "read Complete", Toast.length_short). Show ();
		}
		});  Write.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//TODO auto-generated
				Method Stub Xstreamnode Item = new Xstreamnode ("Letterinfolist", Letterinfolist.class);
				Xstreamnode item1 = new Xstreamnode ("ROWS", Rows.class);
				Xstreamnode item2 = new Xstreamnode ("Appealbase", Letteritem.class); list<xstreamnode> clsz = new Arraylist<xstreamutil.xstrEamnode> ();
				Clsz.add (item);
				Clsz.add (ITEM1);
				Clsz.add (ITEM2);
				String object2xml = Xstreamutil.object2xml (CLSZ, data);
				System.out.println (Object2xml.tostring ());
				Tv_show.settext (Object2xml.tostring ());
				FileOutputStream out = null;
					try {out = new FileOutputStream (New File ("/sdcard/mytest.xml"));
				Out.write (Object2xml.getbytes ());
				catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
				catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
					Finally {try {out.close ();
					catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
	}
				}
			}
		}); }
}

Layout, Main.xml


<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
    android:layout_width=" fill_parent "
    android:layout_height=" fill_parent "
    android:o" rientation= "vertical" >

    <button
        android:id= "@+id/read" android:layout_width= "Fill_parent"
        android:layout_height= "wrap_content"
        android:text= "read SD card XML file"/>

    <button
        android:id= "@ +id/write "
        android:layout_width=" fill_parent "
        android:layout_height=" wrap_content "
        android:text" = "Write SD card XML file"/>

    <scrollview
        android:layout_width= "fill_parent"
        android:layout_height= " Wrap_content ">

        <textview
            android:id=" @+id/show "
            android:layout_width=" Fill_parent " android:layout_height= "Wrap_content"
            android:text= "display text content"/>
    </ScrollView>

</ Linearlayout>

Here is the test diagram effect



Here is the demo download connection

http://download.csdn.net/detail/zgf1991/4517168

Click to open the link

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.