【问题标题】:JAXB unmarshal wrapped listJAXB 解组包装列表
【发布时间】:2018-07-17 08:55:34
【问题描述】:

是否可以在 JAXB 中将包装元素列表直接解组为 List<String>

例如,我有一个类似的 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 文件解组为仅包含 { "foo.png", "bar.png" } 的 List&lt;String&gt;

我知道您可以使用正确的注释创建一个类层次结构来执行此解组,但我希望有这样的代码:

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);

    }   
}

有什么办法吗?

【问题讨论】:

  • JAXB 的预期用途是将整个 XML 解组为对象结构。使用 XPATH 可以更好地满足您的用例。

标签: java xml jaxb


【解决方案1】:

很抱歉这么晚才回答,但如果搜索相关问题,这是谷歌上的第一次点击,所以无论如何它可能会有所帮助。

是的,有可能,使用

@XmlElementWrapper

组合

@XmlElement

请参阅this example 了解更多详细信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多