在我的Android
项目中,我有两个XML
文件,如下所示:
<request>
<target>www.facebook.com</target>
<packetsize>32</packetsize>
<timeout>4</timeout>
...
</request>
和
<response>
<target>www.facebook.com</target>
<packetsize>32</packetsize>
<timeout>4</timeout>
...
</request>
这两个文件都有相同的元素,但根节点不同。使用SimpleXML
框架,我希望创建一个名为PinResponse的新类,作为用于重用/更改响应属性的XML文件中所有元素的容器。为此,我希望将XML模型类中的类作为元素引用。
PinResponse类:
@Element
public class PinResponse {
@Element(name = "target")
private String target;
@Element(name = "packetsize")
private int packetSize;
@Element(name = "timeout")
private int timeout;
...
}
XML模型类:
@Root(name = "request")
public class PingResponseData {
@Element
private PinResponse pinResponse;
public PinResponse getPinResponse() {
return pinResponse;
}
}
但我总是能得到一个ElementException:
org.simpleframework.xml.core.ElementException: Element 'target' does not have a match in class
如何将PinResponse类作为元素添加到XML模型类中?
发布于 2016-03-16 09:08:01
克里斯·拉尔森( Kris answer )帮助我解决了我的问题,这就是我现在的最终解决方案:
基类:(受保护的访问权限以使用子类中的元素)
public abstract class Ping {
@Element(name = "target")
protected String target;
@Element(name = "packetsize")
protected int packetSize;
@Element(name = "timeout")
protected int timeout;
...(getter/setter)
}
请求子类:
@Root(name = "request")
public class PingRequest extends PingRequestResponse {
public PingRequest(Ping ping) {
this.target = ping.getTarget();
this.packetsize = ping.getPacketsize();
this.timeout = ping.getTimeout();
...
}
响应子类:
@Root(name = "response")
public class PingResponse extends PingRequestResponse {
//empty as it has the same elements, if it would have additional fields, they would be added here
}
发布于 2016-03-14 14:28:24
通常情况下,你会这样做:
public abstract class PingRequestResponse {
@Element(name = "target")
private String target;
@Element(name = "packetsize")
private int packetSize;
@Element(name = "timeout")
private int timeout;
...
}
@Root(name = "request")
public class PingRequest extends PingRequestResponse { }
@Root(name = "response")
public class PingResponse extends PingRequestResponse { }
但是,我对SimpleXML的使用还不足以知道这样的子类中注释是否能正确工作。
试试看会发生什么。
https://stackoverflow.com/questions/35987993
复制相似问题