简体   繁体   中英

XML to Java Object with JAXB

I have got XML file which I would like to convert to a Java Object.

I have looked at JAXB, but this XML seems far too complex.

Here store has same elements nested into each other. They don't match, and I am unsure of how I would create the annotation class for this.

<?xml version="1.0" encoding="UTF-8"?>
<store id="1" name="main">
    <store id="2" name="xx">
        <location>here</location>
    </store>
    <store id="3" name="xx">
        <location>here</location>
    </store>
    <store id="56" name="xx">
        <store id="97" name="xx">
            <img>store_image.png</img>
            <store id="101" name="five">
                <img>tore_image.png</img>
                <store id="145" name="xx">
                    <img>tore_image.png</img>
                    <location>here</location>
                </store>
                <store id="252" name="xx">
                    <img>store_image.png</img>
                    <location>here</location>
                </store>
            </store>
        </store>
    </store>
</store>

can you try

@XmlRootElement(name="store")
@XmlAccessorType(XmlAccessType.FIELD)
public class Store {

   // this should take care of nested store elements
   @XmlElement(name="store")
   private List<Store> stores;

   @XmlElement(name="location")
   private String location;

   @XmlElement(name="img")
   private String img;

   @XmlAttribute(name="id")
   private String id;

   @XmlAttribute(name="name")
   private String name;

   // and include getters and setter 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM