2012-05-24 70 views
0

我試圖解析XML文件來使用XStream的對象,但我得到這個異常:在線程Java的XStream的CannotResolveClassException

異常「主」 com.thoughtworks.xstream.mapper.CannotResolveClassException:服務器 在 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(); 

回答

6

嘗試添加類服務器來保存你的SERVERIP實例,並添加此行:

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

在這裏您可以找到別名一個簡單的教程:http://x-stream.github.io/alias-tutorial.html

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

    public String getIp() { 
     return ip; 
    } 

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

對不完整的答案,我分心,並在完成之前發表。同時@Teg指出了這個方向。

+1

使用註釋是一個很好的加在答案上 – Teg