JAXB can not handle XML element containing white s

2019-07-09 03:48发布

I have XML like the following:

<repository>
<location>/home/username whitespace/somedir</location>
</repository>

I am using JAXB to unmarshal this into a JAXB annotated Bean. The "location" XML element is mapped to java.net.URI class. The problem is that when location contains white space, JAXB (or perhaps the underlying XML parser) can't handle this and location is set to null. There is no UnmarshalException or anything, just setLocation(URI loc) is called with a null method argument.

A URI without a white space works correctly of course. The thing is that I can't really change RepositoryDTO to say have String location; field.

Can you tell what are my options here?

Should I look at URLEncode and then Decode the said location field?

This a REST/Jersey use case by the way, although clearly the culprit lies in JAXB/XML parser...

    public class Whitespace {

    public static void main(String[] args) throws JAXBException {
        String xml = "<repository><location>/home/username whitespace/somedir</location></repository>";

        Unmarshaller createUnmarshaller = JAXBContext.newInstance(RepositoryDTO.class).createUnmarshaller();
        RepositoryDTO repositoryInfo = (RepositoryDTO) createUnmarshaller.unmarshal(new StringReader(xml));
        System.out.println(repositoryInfo.getLocation());

    }

    @XmlRootElement(name = "repository")
    static public class RepositoryDTO {
        private URI location;

        @XmlElement
        public URI getLocation() {
            return location;
        }

        public void setLocation(URI loc) {
            this.location = loc;
        }

    }
}

2条回答
劳资没心,怎么记你
2楼-- · 2019-07-09 03:51

Try using the standart URI encoding for whitespace (replace space inside the XML element with %20)

查看更多
Fickle 薄情
3楼-- · 2019-07-09 03:58

You can use this adapter

import java.net.URI;
import java.net.URISyntaxException;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class UriAdapter extends XmlAdapter<String, URI> {

    public URI unmarshal(String s) {
        if(s != null){
            try {
                return new URI(s.replace(" ", "%20"));
            } catch (URISyntaxException e) {
            }
        }
        return null;
    }

    public String marshal(URI uri) {
        return uri.getPath();
    }
}

In this way

@XmlJavaTypeAdapter(UriAdapter.class)
protected URI location;
查看更多
登录 后发表回答