小编典典

如何在具有相同标签名称的Java中解组嵌套的子元素?

spring-boot

在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

阅读 372

收藏
2020-05-30

共1个答案

小编典典

您需要输入以下内容:

@XmlElement(name = "ip_addresses")
private IPAddresses ipAddresses;

和IPAddresses 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());
}
2020-05-30