xstream.useAttributeFor(ChildNav.class,"name");
xstream.useAttributeFor(ChildNav.class,"url");
/**
*@author
*ChildNav属性值转换器
*/
//publicclassChildNavConverterimplementsConverter{
//
//publicvoidmarshal(Objectvalue,HierarchicalStreamWriterwriter,MarshallingContextcontext){
//ChildNavchildNav=(ChildNav)value;
//writer.addAttribute("name",childNav.getName());
//writer.addAttribute("url",childNav.getUrl());
//}
//
//publicObjectunmarshal(HierarchicalStreamReaderreader,UnmarshallingContextcontext){
//ChildNavchildNav=newChildNav();
////city.setName(reader.getValue());
//childNav.setName(reader.getAttribute("name"));
//childNav.setUrl(reader.getAttribute("url"));
//returnchildNav;
//}
//
//publicbooleancanConvert(Classclazz){
//returnclazz.equals(ChildNav.class);
//}
//
//}
/*******************************************************************************************************************/
详细代码解析:
XStreamxstream=newXStream();
Filexml=newFile(fileName);
BufferedReaderreader=newBufferedReader(newInputStreamReader(newFileInputStream(xml),"UTF-8"));
//xml文档中节点映射到对应的类
xstream.alias("childNav",ChildNav.class);
xstream.alias("nav",Nav.class);
xstream.alias("permissions",Permissions.class);
xstream.aliasField("name",Nav.class,"name");
xstream.aliasField("name",ChildNav.class,"name");
xstream.aliasField("url","url");
xstream.useAttributeFor(ChildNav.class,"name");
xstream.useAttributeFor(ChildNav.class,"url");
xstream.useAttributeFor(Nav.class,"name");
//父节点nav对应Nav类,childNav节点对应ChildNav类,有多个childNav节点,这里需转换到集合中
//没有这句的话会报错误“
Causedby: //com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$DuplicateFieldException: //DuplicatefieldchildNav
”
xstream.addImplicitCollection(ChildNav.class,"childNav");
//将一个xml转成java对象
PermissionsObj=(Permissions)xstream.fromXML(reader);//deserializefromXML
//对xml的package包进行别名映射
xstream.aliasPackage("my.company","com.thoughtworks");
XStream提供了Converter,使我们在object<->xml时,能对一些输入输出参数进行类型转换。
默认的情况下,XStream在做转换时,会将整个object转成xml,也会将整个xml转成对象。
对于个别字段或者xml域,可能我们不想做转换,就可以使用omitField 。
xStream.omitField(Person.class,"lastname");
(不会吧Person类里面的属性lastname 解析到xml)
默认情况下,XStream不会自动扫描这种Annotations
stream.processAnnotations(RendezvousMessage.class);(需要加上这句去扫描RendezvousMessage.class里面的注释)