2014-09-03 24 views
2

讓我們假設我們有XML consnensual與Schema和Java類一些常見的領域:兩種不同的模式和JAXB的Marshaller

<objectFromSchema1> 
    <element1/> 
    <commonElement1/> 
    <commonElement2/> 
    <element2/> 
    </objectFromSchema1> 

    public class X { 
    private String element1; 
    private String commonElement1; 
    private String commonElement2; 
    private String element2; 
    } 

就是要unmarschall這類XML到Java對象的好方法?這意味着:轉換所有的合意字段並在休息時設置爲空。

+0

可我知道爲什麼你問這個? 這是一個非常方便和簡單的方法 – Vihar 2014-09-03 06:41:30

回答

1

「YES」

如果你有一個xsd你也可以自動生成這些類由<artifactId>maven-jaxb2-plugin</artifactId> Maven插件。

import java.io.Serializable; 

import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlRootElement; 
import javax.xml.bind.annotation.XmlType; 

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(name = "objectFromSchema1", propOrder = { 

}) 
@XmlRootElement(name = "objectFromSchema1") 
public class ObjectFromSchema1 
implements Serializable 
{ 

    private final static long serialVersionUID = 12343L; 
    protected String element1; 
    protected String element2; 
    protected String commonElement1; 
    protected String commonElement2; 
    public String getElement1() { 
     return element1; 
    } 
    public void setElement1(String element1) { 
     this.element1 = element1; 
    } 
    public String getElement2() { 
     return element2; 
    } 
    public void setElement2(String element2) { 
     this.element2 = element2; 
    } 
    public String getCommonElement1() { 
     return commonElement1; 
    } 
    public void setCommonElement1(String commonElement1) { 
     this.commonElement1 = commonElement1; 
    } 
    public String getCommonElement2() { 
     return commonElement2; 
    } 
    public void setCommonElement2(String commonElement2) { 
     this.commonElement2 = commonElement2; 
    } 

} 

主要方法,使用它你的類的實例

public static void main(String[] args) throws JAXBException { 
     final JAXBContext context = JAXBContext.newInstance(ObjectFromSchema1.class); 
     final Marshaller m = context.createMarshaller(); 
     m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 

     final ObjectFromSchema1 objectFromSchema1 = new ObjectFromSchema1(); 

     objectFromSchema1.setCommonElement1("commonElement1"); 
     objectFromSchema1.setCommonElement2("commonElement2"); 
     objectFromSchema1.setElement1("element1"); 
     objectFromSchema1.setElement2("element2"); 

     m.marshal(objectFromSchema1, System.out); 
    } 

輸出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<objectFromSchema1> 
    <element1>element1</element1> 
    <element2>element2</element2> 
    <commonElement1>commonElement1</commonElement1> 
    <commonElement2>commonElement2</commonElement2> 
</objectFromSchema1>