2012-07-03 74 views
3

我有以下xml格式,我想通过POJO并使用JAXB注释来绑定它。该XML格式如下:使用POJO和JAXB注释绑定XML

<datas> 
    <data>apple<data> 
    <data>banana<data> 
    <data>orange<data> 
<datas> 

我试图绑定通过以下POJO数据:

@XmlRootElement() 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Datas { 

    @XmlElement 
    private List<String> data; 

    //get/set methods 

} 

,也是我尝试这个POJO:

@XmlRootElement() 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Datas { 

    @XmlElement 
    private List<Data> datas; 

    //get/set methods 

} 

//

@XmlRootElement() 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Data{ 

    @XmlElement 
    private String data; 

    //get/set methods 

} 

在fi第一种情况它只检索第一个数据:苹果。在第二种情况下不检索任何东西。有人可以帮助我提供适当的POJO和注释以绑定所有数据吗?

回答

4

您可以执行下列选项之一:

选项#1

DATAS

package forum11311374; 

import java.util.List; 
import javax.xml.bind.annotation.*; 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Datas { 

    private List<String> data; 

    //get/set methods 

} 

更多信息


选项#2

DATAS

package forum11311374; 

import java.util.List; 
import javax.xml.bind.annotation.*; 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Datas { 

    @XmlElement(name="data") 
    private List<Data> datas; 

    //get/set methods 

} 

数据

package forum11311374; 

import javax.xml.bind.annotation.*; 

@XmlAccessorType(XmlAccessType.FIELD) 
public class Data{ 

    @XmlValue 
    private String data; 

    //get/set methods 

} 

更多信息


以下可以与两个选项一起使用:

input.xml中/输出继电器

我已更新XML文档以包含必要的结束标记。 <data>apple</data>而不是<data>apple<data>

<datas> 
    <data>apple</data> 
    <data>banana</data> 
    <data>orange</data> 
</datas> 

演示

package forum11311374; 

import java.io.File; 
import javax.xml.bind.*; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Datas.class); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     File xml = new File("src/forum11311374/input.xml"); 
     Datas datas = (Datas) unmarshaller.unmarshal(xml); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(datas, System.out); 
    } 

} 
1

第一个选项没有工作对我来说...不知道为什么你所得到的问题...... 试试这个注释...

@XmlElements(@XmlElement(name="data", type=String.class)) 
private List<String> datas; //ignore the variable name 
+0

'@ XmlElements'对应于XML模式中'xsd:choice'的概念,并不是此特定用例的正确注释。欲了解更多信息,请参阅:http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html –