0

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.

5
  • 1
    Possible duplicate of Parse XML string and build a list of strings Commented Nov 30, 2018 at 12:39
  • There must be a problem different from the conversion by split(", ") and Array.asList. Does your xml parser work correctly? I just tried to split a String listAsString = "A, B, C, D" with your Arrays.asList(words.split(", ")) and it worked. Commented Nov 30, 2018 at 12:45
  • @Abhinav - That is a different question. Commented Nov 30, 2018 at 12:51
  • @deHaar - That conversion works fine. But while parsing it is not giving correct result. I should have missed something while parsing. Is there any way to do this in JAXB? Commented Nov 30, 2018 at 12:54
  • Show us your parsing code, please... Commented Nov 30, 2018 at 12:56

1 Answer 1

0

Finally I have figured out the problem and found the solution to get array of strings instead of list of strings.

private String[] words;

@XmlElement(name="Words")
public void setWords(String[] words) {
    /* Converting String to Array */
    this.words = words[0].split(", ");
}

The problem was method parameter type(String) and variable type(List<String>) were not same. It should be same in order to parse it correctly. I have changed both of them to String[] and put my logic in setter. Now the string in XML is parsed into String[].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.