我有如下 XML:
<repository>
<location>/home/username whitespace/somedir</location>
</repository>
我正在使用 JAXB 将其解码到 JAXB 带注释的 Bean 中。
“location”XML 元素映射到 java.net.URI 类。
问题是,当 location 包含空格时,JAXB(或者可能是底层 XML 解析器)无法处理此问题,并且 location 被设置为 null
。没有 UnmarshalException
或任何东西,只是使用 null
方法参数调用 setLocation(URI loc)
。
没有空格的 URI 当然可以正常工作。
问题是我无法真正更改 RepositoryDTO
来表示具有 String location;
字段。
你能告诉我这里有什么选择吗?
我应该查看 URLEncode,然后解码所述 location
字段吗?
顺便说一句,这是一个 REST/Jersey 用例,尽管罪魁祸首显然在于 JAXB/XML 解析器......
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;
关于java - JAXB 无法处理包含空格的 XML 元素到 java.net.URI 的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33258711/