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



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

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[]

最新更新