XStream使用之终结

下面就是为了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>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值