在Java中,我可以通过将值添加到我的POJO中来读取XML。但我不知道如何才能对子子节点做同样的事情。我提供了我的POJO示例和XML子类节点。
XML:
<results>
<rootNode>
<node>1336</node>
<state>CL</state>
<time>0</time>
<ip_addresses>
<ip_address type="DOC">06:56:43.0</ip_address>
<ip_address type="PE">06:56:43.0</ip_address>
</ip_addresses>
<lease_date>2017-01-25</lease_date>
</rootNode>
</results>
POJO:
@XmlRootElement(name = "rootNode")
@XmlAccessorType (XmlAccessType.FIELD)
public class readingXml
{
private int id;
@XmlElement(name = "node")
private String node;
@XmlElement(name = "state")
private String state;
// How to do the same with sub child-nodes
@XmlElement(name = "ip_addresses")
private String ip_addresses;
// What to do here?
@XmlElement(name = "lease_date")
private String lease_date;
// Getters and setters for all above
答案 0 :(得分:4)
你需要这样的东西:
@XmlElement(name = "ip_addresses")
private IPAddresses ipAddresses;
和IP地址POJO类:
@XmlRootElement(name = "ip_addresses")
@XmlAccessorType(XmlAccessType.FIELD)
public class IPAddresses implements Serializable {
private final static long serialVersionUID = 1L;
@XmlElement(name = "ip_address")
private List<IPAddress> ipAddresses;
public List<IPAddress> getIpAddresses() {
return ipAddresses;
}
public void setIpAddresses(List<IPAddress> ipAddresses) {
this.ipAddresses = ipAddresses;
}
}
其中IPAddress是描述单个元素结构的另一个POJO类。
@XmlRootElement(name = "ip_address")
@XmlAccessorType(XmlAccessType.FIELD)
public class IPAddress implements Serializable {
private final static long serialVersionUID = 1L;
@XmlValue
protected String content;
@XmlAttribute(name = "type")
protected String type;
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setType(String content) {
this.type = type;
}
public String getType() {
return type;
}
}
修改强> 要打印它们,请执行以下操作:
for (IPAddress ipAddress in custinfo.getIpAddresses().getIpAddresses()) {
System.out.println("value: " + ipAddress.getContent());
System.out.println("type: " + ipAddress.getType());
}
答案 1 :(得分:1)
您可以将“ip_addresses”的类型从String更改为另一个POJO类。
E.g。
@XmlElement(name = "ip_addresses")
private List<Address> ip_addresses;
然后将您的地址POJO定义为
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "ip_addresses")
public class Address {
@XmlElement(type = "DOC")
protected String ip_address1;
@XmlElement(type = "PE")
protected String ip_address2;
public String getIp_address1() {
return ip_address1;
}
public void setIp_address1(String value) {
this.ip_address1= value;
}
public String getIp_address2() {
return ip_address2;
}
public void setIp_address2(String value) {
this.ip_address2= value;
}
}