简体   繁体   中英

How to map a XML ignoring namespace using JAXB?

I'm receiving a XML from a web service with the following format:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<string xmlns="http://someurl.com">somethingheresomethinghere</string>

And I'm trying to unmarshall this to a POJO that looks like this:

@XmlRootElement(name="string")
public class StringValue {

    @XmlValue
    private String value;

    public StringValue () {
    }
}

And my unmarshalling code is this:

public T xmlToObject(Class<T> contextPath, Reader reader) throws Exception {
    JAXBContext context = JAXBContext.newInstance(contextPath);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setEventHandler(new XMLValidationEventHandler());
    T objectToConvert = (T) unmarshaller.unmarshal(reader);
    return objectToConvert;
}

But I'm getting the following error:

unexpected element (uri:" http://someurl.com ", local:"string"). Expected elements are <{}string>

If the namespace in the XML were to be omitted from it, then it will work, but instead of altering the XML I want to know how can I make it so the namespace part doesn't cause me any trouble when marshalling or unmarshalling with JAXB.

How can I achieve this behaviour?

You can map the namespace using the package level @XmlSchema annotation.

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

import javax.xml.bind.annotation.*;

For More Information

I have written more about JAXB and namespace qualification on my blog:

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