1. java程序中使用xstream方法将实体类转成xml,实体类中有null值,生成的xml就去除了含有null值的节点!
XStream 用法详解 java 类与 XML 互换
现在 WEB数据交换的时代,传送XML目前是一个比较流行的方式,具有统一的规则约束,为实现后台接口提供了一个很方便的实现。
我编写了一个 接收XML并转换成所需要的Object类的 小例子,希望能够对做互联网数据传输、接口调用的朋友有所帮助。
首先要导入jar包xstream-1.4.3-sources.jar 和 xmlpull-1.1.3.1.jar 两个包;
其次是预备一个 XML 事例
[html] view plain
<config>
<span style="white-space:pre"> </span><client type="8888" osversion="9999" version="123" oemtag="5555" area="areacode"/>
<span style="white-space:pre"> </span><protocol>1.10</protocol>
<span style="white-space:pre"> </span><sign value="asdfasdf"/>
<span style="white-space:pre"> </span><vientiance version="version"/>
</config>
其次 就是 按照 XML节点的顺序 从外 到内 编写 java PO类,此实例的目的是将上面的XML转换为 AllnewstateRQ 这个实体类,然后从里面打印出测试数据。
下面依次是 config节点 对应的 AllnewstateRQ类 ; client 节点 对应的 Client 类;sign 节点对应的 Sign类;vientiance 节点 对应的 Vientiance类。
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("config")
public class AllnewstateRQ {
//当节点下有独立属性的时候,需要创建一个独立的类用来保存节点内的属性
private Client client = new Client();
private Sign sign = new Sign();
private Vientiance vientiance = new Vientiance();
//当节点下没有属性,直接由StringValue的时候可直接创建String类型属性
private String protocol;
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Sign getSign() {
return sign;
}
public void setSign(Sign sign) {
this.sign = sign;
}
public Vientiance getVientiance() {
return vientiance;
}
public void setVientiance(Vientiance vientiance) {
this.vientiance = vientiance;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
}
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
@XStreamAlias("client")
public class Client {
@XStreamAsAttribute //对属性值进行注解
private String type;//此时类中的属性名要和xml内的属性名相对应
@XStreamAsAttribute
private String osversion;
@XStreamAsAttribute
private String version;
@XStreamAsAttribute
private String oemtag;
@XStreamAsAttribute
private String area;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOsversion() {
return osversion;
}
public void setOsversion(String osversion) {
this.osversion = osversion;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getOemtag() {
return oemtag;
}
public void setOemtag(String oemtag) {
this.oemtag = oemtag;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
}
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
@XStreamAlias("sign") //此处要对应节点的名称
public class Sign {
@XStreamAsAttribute
private String value;//此处对应节点内属性名称
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
@XStreamAlias("vientiance")
public class Vientiance {
@XStreamAsAttribute
private String version;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
测试main方法
[java] view plain
package com.wgq.test09_xml;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class TestStream {
public static void main(String[] args) {
String reqXml = getXml();
XStream xs = new XStream(new DomDriver());
xs.processAnnotations(new Class[]{AllnewstateRQ.class,Client.class,Sign.class,Vientiance.class});
Object obj = xs.fromXML(reqXml);
AllnewstateRQ allnewstateRQ = (AllnewstateRQ) obj;
System.out.println(allnewstateRQ.getProtocol());
System.out.println(allnewstateRQ.getClient().getArea());
System.out.println(reqXml);
}
static String getXml(){
StringBuilder str = new StringBuilder();
str.append("")
.append("<config>")
.append("<client type=\"8888\" osversion=\"9999\" version=\"123\" oemtag=\"5555\" area=\"areacode\" />")
.append("<protocol>1.10</protocol>")
.append("<sign value=\"asdfasdf\" />")
.append("<vientiance version=\"version\" />")
.append("</config>")
;
return str.toString();
}
}
输出结果:
[java] view plain
1.10
areacode
<config><client type="8888" osversion="9999" version="123" oemtag="5555" area="areacode" /><protocol>1.10</protocol><sign value="asdfasdf" /><vientiance version="version" /></config>
2. 用XStream 转换java对象成xml的一个疑问
3. java用XStream把xml转换成javabean的问题
xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换;它们都完美支持JSON,但是对xml的支持还不是很好。一定程度上限制了对Java对象的描述,不能让xml完全体现到对Java对象的描述。这里将会介绍xStream对JSON、XML的完美支持。xStream不仅对XML的转换非常友好,而且提供annotation注解,可以在JavaBean中完成对xml节点、属性的描述。以及对JSON也支持,只需要提供相关的JSONDriver就可以完成转换。
4. java通过xstream解析xml,这样的节点bean对象应该如何创建
用 xstream 生成一个.xml 你就知道了。
5. xStream转换xml同名节点到java对象问题
假设XML文件(config/0_student.xml)内容如下:
<students>
<student>
<name>zhang3</name>
<age>20</age>
</student>
<student>
<name>li4</name>
<age>21</age>
</student>
</students>
XStream转换代码如下:
{
publicvoidtestToObject()throwsException{
XStreamxstream=newXStream(newDomDriver());
Filefile=newFile(XStreamUtil.class.getClassLoader().getResource("").getPath(),"config/0_student.xml");
xstream.alias("students",List.class);
xstream.alias("student",Student.class);
List<Student>students=(List<Student>)xstream.fromXML(newFileInputStream(file));
assertEquals(2,students.size());
assertEquals("zhang3",students.get(0).getName());
assertEquals("li4",students.get(1).getName());
assertEquals(20,students.get(0).getAge());
assertEquals(21,students.get(1).getAge());
}
}
6. xstream xml转化成java对象
注意事项:
创建接收转换的实体类 里面字段 与 xml节点一一对应。spring 使用@XStreamAlias("节点") 进行关联。属性名与节点一一对应是很重要的!!!不然 不能正常转换。使用了注解以后,xml节点跟类的属性名不再有关系,但是 注解里面使用的名字就默认是与xml节点对应的。所以保持@XStreamAlias("节点") 里面节点的值与xml 一一对应。
xstream.processAnnotations(需要转化的实体类.class);
实体类 例子:
package com.cmsz.cmup.alipay.model.responses;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;
/**
* @Title: AccountResultVO.java
* @Package com.cmsz.cmup.alipay.vo.result
* @Description: alipay返回xml字符串封装对象
* @author yekun
* @date 2015年12月4日 上午10:50:23
*/
@XStreamAlias("alipay")
public class AccountResponseModel {
/** 错误信息 */
@XStreamAlias("error")
private String error;
/** 请求是否成功 */
@XStreamAlias("is_success")
private String isSuccess;
/** 请求参数 */
@XStreamAlias("request")
private Request request;
/** xml节点 */
@XStreamAlias("response")
private Response response;
/** 签名 */
@XStreamAlias("sign")
private String sign;
/** 签名加密方式 */
@XStreamAlias("sign_type")
private String sign_type;
//转换代码
XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(实体类.class);
xstream.fromXML(xmlStr);//xml格式的字符串
7. jsp Form->Java Bean ->使用XStream->生成XML文件
[代码]1.实体类:PersonBean
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("person")
public class PersonBean {
@XStreamAlias("firstName")
private String firstName;
@XStreamAlias("lastName")
private String lastName;
@XStreamAlias("telphone")
private PhoneNumber tel;
@XStreamAlias("faxphone")
private PhoneNumber fax;
//省略setter和getter }
main函数示例1:toxml
import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JsonWriter.Format; import com.thoughtworks.xstream.io.xml.DomDriver;
public class PersonTest {
public static void main(String[] args) {
PersonBean per=new PersonBean();
per.setFirstName("chen");
per.setLastName("youlong");
PhoneNumber tel=new PhoneNumber();
tel.setCode(137280);
tel.setNumber("137280968");
PhoneNumber fax=new PhoneNumber();
fax.setCode(20);
fax.setNumber("020221327");
per.setTel(tel);
per.setFax(fax);
//java对象转换成xml
String xml=XmlUtil.toXml(per);
System.out.println("xml==="+xml);
}
}
main函数示例2:toBean
public static void main(String[] args) {
String xmlStr="<person>"+
"<firstName>chen</firstName>"+
"<lastName>youlong</lastName>"+
"<telphone>"+
"<code>137280</code>"+
"<number>137280968</number>"+
"</telphone>"+
"<faxphone>"+
"<code>20</code>"+
"<number>020221327</number>"+
"</faxphone>"+
"<friends>"+
"<name>A1</name>"+
"<name>A2</name>"+
"<name>A3</name>"+
"</friends>"+
"<pets>"+
"<pet>"+
"<name>doly</name>"+
"<age>2</age>"+
"</pet>"+
"<pet>"+
"<name>Ketty</name>"+
"<age>2</age>"+
"</pet>"+
"</pets>"+
"</person>"; //用泛型的知识
PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
System.out.println("person=firstname=="+person.getFirstName());
System.out.println("person==Friends==name1=="+person.getFriend().getName().get(0));
System.out.println("person==Pets==name2=="+person.getPet().getAnimalList().get(1).getName());
}
8. XStream将java对象转换为xml时,对象字段中的下划线“_”,转换后变成了两个
warning: [deprecation] XppDriver(com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer) in com.thoughtworks.xstream.io.xml.XppDriver has been deprecated
已经过时的方法,所以,不会调用此方法。