简体   繁体   中英

XML to Java JaxB

My attempt to convert an XML to Java using JAXB not working as expected. There are multiple other similar questions around it but none of the suggested solutions I looked into seem to help me.

Below is my bean

@XmlRootElement(name = "ListingResponse", namespace = "http://www.random.com")
@XmlType(propOrder = {"success", "listingId", "description"})
public class ListingResponse {
    private String success;
    private String listingId;
    private String description;


    public String getSuccess() {
        return success;
    }

    @XmlElement(name = "Success")
    public void setSuccess(String success) {
        this.success = success;
    }

    public String getListingId() {
        return listingId;
    }

    @XmlElement(name = "ListingId")
    public void setListingId(String listingId) {
        this.listingId = listingId;
    }

    public String getDescription() {
        return description;
    }

    @XmlElement(name = "Description")
    public void setDescription(String description) {
        this.description = description;
    }

Below is my attempt to do the unmarshaling

ListingResponse response = null;
try {
    JAXBContext jaxbContext = JAXBContext.newInstance(ListingResponse.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    response = (ListingResponse) jaxbUnmarshaller.unmarshal(new File("response.xml"));

} catch (JAXBException e) {
    e.printStackTrace();
}

And finally my response.xml content

<ListingResponse xmlns="http://www.random.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Success>true</Success>
    <Description>ListingId 123 created.</Description>
    <ListingId>123</ListingId>
</ListingResponse>
  1. There are not exceptions being thrown.
  2. ' response ' is NOT null.
  3. I have tried adding @XmlAccessorType(XmlAccessType.FIELD / PROPERTY) with @XMLEelement annotation on the fields/ set methods but that didn't seem to help either.

However, response is always 'empty' with none of the fields initialized.

Can you guys spot the issue here?

Currently you only have specified the correct namespace qualification for the root element. You need to use the package level @XmlSchema annotation to map the namespace qualification for your model.

package-info.java

@XmlSchema( 
    namespace = "http://www.random.com", 
    elementFormDefault = XmlNsForm.QUALIFIED) 
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

For More Information

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