2015-03-25 91 views
1

我正在使用JAXB将java对象编组为XML。我已经从xsd生成了所需的java对象。我能够编组并获得如下所述的XML。Jaxb marshalling - 从java对象获取xml中的所有字段

<Disk> 
<Details> 
    <status>attached</status> 
    <size>10000000000</size> 
    <freeSpace>25600000<freeSpace> 
    <id>MI45563PO</id> 
</Details> 
</Disk> 

但是,xml只包含字段,为此需要在模式中设置值和必填字段(默认值)。我需要在xsd中定义的所有字段(为空)以及为其设置值的字段。

Java代码:

Disk disk = new Disk(); 
    Details details = new Details(); 
    details.setSize(100000000); 
    details .setDetails(details); 

    JAXBContext context = JAXBContext.newInstance("com.samplefile");   

    Marshaller marshaller = context.createMarshaller(); 

    marshaller.setProperty("jaxb.formatted.output",Boolean.TRUE); 

    marshalle.marshal(details ,new FileOutputStream(new       
    File("C:/test/Sample.xml"))); 

任何帮助表示赞赏。

回答

1

你应该把注释

@XmlElement(nillable=true) 

在类的细节,可以为空的所有字段。 例如

@XmlElement(nillable=true) 
public String getStatus() { 
    return status; 
} 

如果该字段包含空值的输出将是:

<status xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>