android XMl 解析神奇xstream 三: 把复杂对象转换成 xml

时间:2022-10-27 23:33:01

前言:对xstream不理解的请看:

android XMl 解析神奇xstream 一: 解析android项目中 asset 文件夹 下的 aa.xml 文件

android XMl 解析神奇xstream 二: 把对象转换成xml

1、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;
}
}

2、主要方法

package com.android10;
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 ); Person person = new Person() ;
person.setpName( "saliy" ) ;
person.setpAge( "36" ); Product product = new Product() ;
product.setName( "jhon" ) ;
product.setAge( "30" );
product.setPerson( person ); System.out.println("sss " + product.getName() + product.getAge() ); //把对象转化为 XML
XStream xstream1 = new XStream();
String string = xstream1.toXML( product ) ;
System.out.println( "sss"+ string ); //把对象转化为 XML,并且设置别名
XStream xstream2 = new XStream();
xstream2.alias( "blog" , Product.class ) ; //修改别名
String string2 = xstream2.toXML( product ) ;
System.out.println( "sss"+ string2 );
}
}

3、运行结果

<com.android10.Product>
<age>30</age>
<name>jhon</name>
<person>
<pAge>36</pAge>
<pName>saliy</pName>
</person>
</com.android10.Product> <blog>
<age>30</age>
<name>jhon</name>
<person>
<pAge>36</pAge>
<pName>saliy</pName>
</person>
</blog>

4、代码下载

http://download.csdn.net/detail/yanzi2015/8800411