如何在 Java 中使用 JAXB 将 XML 字符串解组到列表

How to unmarshel XML String to List using JAXB in Java

我正在使用 JAXB 将 XML 解组为 java 对象。我不知道如何将 XML 元素中的字符串解组到列表中。这是我试过的:

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

我的XML:

<Words>A, B, C, D</Words>

代码给出的不是 List,而是 null。如果我将单词的类型从 List 更改为 String,那么它工作正常。是否可以从字符串转换为列表或数组?

XML解析代码:

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:链接的另一个问题与此不同,这里我试图从 XML 元素(单个元素)中获取字符串并将其拆分并存储在列表中。而在另一个问题中,问题是拆分 XML 字符串并将一些元素存储在列表中。

最后我找到了问题并找到了获取字符串数组而不是字符串列表的解决方案。

private String[] words;

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

问题是方法参数类型(String)和变量类型(List<String>)不一样。它应该相同才能正确解析它。我已经将它们都更改为 String[] 并将我的逻辑放在 setter 中。现在 XML 中的字符串被解析为 String[].