是否可以直接将包装元素列表解码为List<String>
在 JAXB 中?
例如,我有一个类似以下的 XML:
<TEST>
<MIME_INFO>
<MIME>
<MIME_SOURCE>foo.png</MIME_SOURCE>
<MIME_PURPOSE>normal</MIME_PURPOSE>
</MIME>
<MIME>
<MIME_SOURCE>bar.png</MIME_SOURCE>
<MIME_PURPOSE>normal</MIME_PURPOSE>
</MIME>
</MIME_INFO>
</TEST>
那么是否可以直接将此 XML 文件解码为 List<String>
只包含 { "foo.png", "bar.png"}?
我知道您可以使用正确的注释创建一个类层次结构来执行此解码,但我想要这样的代码:
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "TEST")
@XmlAccessorType (XmlAccessType.FIELD)
public class Info {
// -> what annotation to put here?
private List<String> infos;
public List<String> getInfos() {
return infos;
}
}
主文件:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class UnmarshallingJAXB {
public static void main(String[] args) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Info.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Info info = (Info) jaxbUnmarshaller.unmarshal(new File("test.xml"));
// should output foo.png and bar.png
info.getInfos().forEach(System.out::println);
}
}
有什么办法可以做到这一点吗?
最佳答案
很抱歉这么晚才回答,但如果搜索相关问题,这是 Google 上的第一个点击,因此无论如何它可能会有所帮助。
是的,这是可能的,使用
@XmlElementWrapper
组合
@XmlElement
参见this example了解更多详细信息。
关于java - JAXB 解码包装列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51377104/