下面就是为了Author属性得以正确显示定义的Converter
package org.mm;
import org.mm.bean.Author;
import com.thoughtworks.xstream.converters.SingleValueConverter;
public class AuthorConverter implements SingleValueConverter{
public String toString(Object obj) {
return ((Author) obj).getName();
}
public Object fromString(String name) {
return new Author(name);
}
public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
return type.equals(Author.class);
}
}
这里就是主类了,到这里程序也就告一段落了 ,以后可能继续对xml有深入了解
package org.mm;
import java.io.File;import org.mm.bean.Detail;
import org.mm.bean.Info;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class ParseComplicated {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//System.err.println(System.getProperty("user.dir"));
/* InputStream in = new FileInputStream("./xml/complexToParse.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String temp = br.readLine();
StringBuffer sb = new StringBuffer();
while(temp!=null){
sb.append(temp);
temp = br.readLine();
}
System.out.println(sb.toString());*/
File f =new File("./xml/complexToParse.xml");
XStream xstream = new XStream(new DomDriver());
xstream.alias("Info",Info.class);
/*
* 下面两句是将集合加入的,先声明Detail类,然后
* 将Detail类变为基础类加入到主类中去
*/
xstream.alias("Detail", Detail.class);
xstream.addImplicitCollection(Info.class, "Details");
/*
* 下面是把author作为属性添加到xml中去
*/
xstream.useAttributeFor(Info.class, "author");
xstream.registerConverter(new AuthorConverter());
// Info info = (Info)xstream.fromXML(sb.toString());
Info info = (Info)xstream.fromXML(f);
System.out.println(info);
System.out.println("\n"+xstream.toXML(info));
}
}
程序运行的结果如下
Info [author=Author [name=wind], Id=102, Name=xiaoQ, QQ=1966767119, Phone=15601584119, Detail=[Message [Message=fish is good !], Message [Message=I am xiaoQ !], Message [Message=q7forever@163.com !]]]
<Info author="wind">
<Id>102</Id>
<Name>xiaoQ</Name>
<QQ>1966767119</QQ>
<Phone>15601584119</Phone>
<Detail>
<Message>fish is good !</Message>
</Detail>
<Detail>
<Message>I am xiaoQ !</Message>
</Detail>
<Detail>
<Message>q7forever@163.com !</Message>
</Detail>
</Info>