Java XStream CannotResolveClassException

时间:2012-05-24 15:08:07

标签: java xml parsing xstream

我正在尝试使用XStream将XML文件解析为对象,但我得到了这个异常:

  

线程“main”中的异常   com.thoughtworks.xstream.mapper.CannotResolveClassException:servers     在   com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:56)     在   com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)     在   com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:55)   [...]

这是我的XML:

  <servers>
    <server>
      <ip>10.196.113.27</ip> 
    </server>
    <server>
      <ip>10.196.113.31</ip> 
    </server>
  </servers>

这是我的代码:

public class ServerIP {
    private String ip;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }
}

public class ServerHandler {

    private String fileName = "servers.xml";
    private String path = "J:\\workspace\\LOG730\\src\\Q3\\";
    private XStream xstream = new XStream(new DomDriver());

    public void readFromXML() {
        try {
            FileInputStream fis = new FileInputStream(path + fileName);
            ServerIP server = (ServerIP) xstream.fromXML(fis, new ServerIP());
            System.out.println("Host: " + server.getIp());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

由此触发异常:

    ServerHandler serverHandler = new ServerHandler();
    serverHandler.readFromXML();

2 个答案:

答案 0 :(得分:6)

尝试添加类Servers来保存您的ServerIP实例并添加以下行:

xstream.alias("servers", Servers.class);
xstream.alias("server", ServerIP.class);

在这里,您可以找到有关别名的简单教程:http://x-stream.github.io/alias-tutorial.html

答案 1 :(得分:3)

@XStreamAlias("server")
public class ServerIP {
    private String ip;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }
}

对不完整的回答感到抱歉,在完成之前我分心并发布了。与此同时,@ Teg指出了这个方向。