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;
}
}
}
Try using the standart URI encoding for whitespace (replace space inside the XML element with %20)
You can use this adapter
In this way