I am working on unmarshalling an XML into java object using JAXB. I don't know how to unmarshal a string in an XML element into List. This is what I have tried:
private List<String> words;
public List<String> getWords() {
return words;
}
@XmlElement(name="Words")
public void setWords(String words) {
/* Converting String to List */
this.words = Arrays.asList(words.split(", "));
}
My XML:
<Words>A, B, C, D</Words>
Instead of List, the code gives me null. If I change the type of words from List to String, then it is working fine. Is it possible to convert from String to List or array?
XML parsing code:
File file = new File("path\\to\\xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Myclass.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Myclass xmlContent = (Myclass) jaxbUnmarshaller.unmarshal(file);
System.out.println(xmlContent.getWords());
PS: The other question linked is different from this, here I am trying to get the String from XML element(a single element) and split and store it in a list. Whereas in the other, the question was splitting the XML string and storing some elements in list.
split(", ")andArray.asList. Does your xml parser work correctly? I just tried to split aString listAsString = "A, B, C, D"with yourArrays.asList(words.split(", "))and it worked.