JAXB:如何在包装器中解组不同类型的对象列表?

时间:2017-10-13 10:55:14

标签: java jaxb

我坚持使用JAXB解析以下xml:

<?xml version="1.0" encoding="utf-8"?>
<dashboardreport name="exampleDashboard" version="6.5.6.1013" reportdate="2016-12-16T11:05:19.329+01:00" description="">
    <data>
        <incidentchartdashlet name="Incident Chart" description="" />
        <chartdashlet name="WebRequestTime" showabsolutevalues="false" />
        <chartdashlet name="WebServiceTime" showabsolutevalues="false" />
    </data>
</dashboardreport>

我使用以下java类来解组xml: Dashboardreport.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "dashboardreport")
public class Dashboardreport {

    @XmlElementWrapper(name = "data")
    @XmlElement(name = "chartdashlet")
    protected List<Chartdashlet> chartdashlets;

    @XmlElementWrapper(name = "data")
    @XmlElement(name = "incidentchartdashlet")
    protected List<Incidentchartdashlet> incidentchartdashlets;

    @XmlAttribute(name = "name")
    protected String name;
}

我只是想在不使用incidentchartdashlets和chartdashlet的包装类的情况下解组xml,因为这两种类型差别很大。 我只能使用XmlElementWrapper注释一次,这样只有chartdashlets被填充而且incidentchartdashlets为null。 有没有使用单独的包装类的JAXB有什么解决方案吗?

1 个答案:

答案 0 :(得分:2)

我假设您的dashlet类定义为 async Task CreateDirectory(string path) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path); request.Method = WebRequestMethods.Ftp.MakeDirectory; using (var response = (FtpWebResponse)(await request.GetResponseAsync())) { Console.WriteLine($"Created: {path}"); } } class Chartdashlet extends Dashlet

然后,首选的JAXB方式来处理混合的dashlet列表 使用@XmlElements 注释:

class Incidentchartdashlet extends Dashlet