I am trying to parse an XML file to objects using XStream but I am getting this exception:
Exception in thread "main" com.thoughtworks.xstream.mapper.CannotResolveClassException: servers at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:56) at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30) at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:55) [...]
Here is my XML:
<servers>
<server>
<ip>10.196.113.27</ip>
</server>
<server>
<ip>10.196.113.31</ip>
</server>
</servers>
Here is my code:
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();
}
}
The exception is triggered by this:
ServerHandler serverHandler = new ServerHandler();
serverHandler.readFromXML();
Try to add a class Servers to hold your ServerIP instances and to add this lines:
xstream.alias("servers", Servers.class);
xstream.alias("server", ServerIP.class);
Here you can find a simple tutorial on the aliases: http://x-stream.github.io/alias-tutorial.html