JAXB无法处理包含空格的XML元素到java.net.URI映射 [英] JAXB can not handle XML element containing white space to java.net.URI mapping

查看:188
本文介绍了JAXB无法处理包含空格的XML元素到java.net.URI映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下XML:

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

我正在使用JAXB将其解组为JAXB注释Bean。
locationXML元素映射到 java.net.URI 类。
问题是当location包含空格时,JAXB(或者可能是底层的XML解析器)无法处理这个,并且location设置为 null 。没有 UnmarshalException 或任何东西,只需 setLocation(URI loc)使用 null调用方法参数。

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.

当然,没有空格的URI可以正常工作。
问题是我无法真正改变 RepositoryDTO 来说字符串位置; 字段。

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?

我应该看看URLEncode然后解码所说的 location field?

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

顺便说一下,这是一个REST / Jersey用例,尽管明显的罪魁祸首在于JAXB / XML解析器...

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

    }
}


推荐答案

您可以使用此适配器

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();
    }
}

这样

@XmlJavaTypeAdapter(UriAdapter.class)
protected URI location;

这篇关于JAXB无法处理包含空格的XML元素到java.net.URI映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆