How to unmarshal nested child elements in java with same tag name?

前端 未结 2 387
不知归路
不知归路 2020-12-11 08:16

In Java I am able to read XML by adding the values into my POJO. But I am not sure how would I able to do the same with sub-child nodes. I provided my POJO example and the X

相关标签:
2条回答
  • 2020-12-11 09:04

    You can change the type of "ip_addresses" from String to another POJO class.

    E.g.

       @XmlElement(name = "ip_addresses")
        private List<Address> ip_addresses;
    

    And then define your Address POJO as

    @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;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-11 09:08

    You need to put something like this:

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

    and IPAddresses POJO class:

    @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;
        }
    }
    

    Where IPAddress is another POJO class that describes the structure of the individual element.

    @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;
        }
    }
    

    EDIT To print them do something like this:

    for (IPAddress ipAddress in custinfo.getIpAddresses().getIpAddresses()) {
        System.out.println("value: " + ipAddress.getContent());
        System.out.println("type: " + ipAddress.getType());
    }
    
    0 讨论(0)
提交回复
热议问题