2015-11-20 21 views
9

@ XmlRootElementアノテーションなしでクラスに対してアンマーシャリングできる方法はありますか?または、注釈を入力する義務はありますか?例えばXmlRootElementアノテーションなしのJAXBアンマーシャリング?

public class Customer { 

    private String name; 
    private int age; 
    private int id; 

    public String getName() { 
     return name; 
    } 

    @XmlElement 
    public void setName(String name) { 
     this.name = name; 
    } 

    public int getAge() { 
     return age; 
    } 

    @XmlElement 
    public void setAge(int age) { 
     this.age = age; 
    } 

    public int getId() { 
     return id; 
    } 

    @XmlAttribute 
    public void setId(int id) { 
     this.id = id; 
    } 

} 

し、適切に注釈付きクラスのアンマーシャルのコードは次のようになりましょう:詳細を残し

try { 

     File file = new File("C:\\file.xml"); 
     JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); 

     Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
     Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); 
     System.out.println(customer); 

     } catch (JAXBException e) { 
     e.printStackTrace(); 
     } 

答えて

18

コードは、コードの上に整列化と非整列化withot @XmlRootElement

public static void main(String[] args) { 

     try { 

      StringWriter stringWriter = new StringWriter(); 

      Customer c = new Customer(); 
      c.setAge(1); 
      c.setName("name"); 

      JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); 

      Marshaller marshaller = jaxbContext.createMarshaller(); 
      marshaller.marshal(new JAXBElement<Customer>(new QName("", "Customer"), Customer.class, null, c), stringWriter); 

      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
      InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes()); 
      JAXBElement<Customer> customer = (JAXBElement<Customer>) jaxbUnmarshaller.unmarshal(new StreamSource(is),Customer.class); 

      c = customer.getValue(); 

      } catch (JAXBException e) { 
      e.printStackTrace(); 
      } 

} 

に使用されている以下のすべての属性をCustomerクラスに@XmlAccessorType(XmlAccessType.PROPERTY)を追加、またはプライベートにする場合にのみ機能します。

+0

、そうでない場合またはXmlRootElement''なし、JAXBはない '除き、他の注釈を必要としませんあなた前述したように – Xstian

+1

を働くん@ XmlAttribute'と '@XmlElement'が出力を記述する – Xstian

+0

アンマーシャリングする前にマーシャリングする必要がありますか? –

1

既存のBeanにXmlRootElementを追加できない場合は、ホルダークラスを作成し、XmlRootElementとしてアノテーションを付けてマークすることもできます。以下の例: -

`private`すべての属性を作成するための代替試みで
import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class CustomerHolder 
{ 
    private Customer cusotmer; 

    public Customer getCusotmer() { 
     return cusotmer; 
} 

    public void setCusotmer(Customer cusotmer) { 
     this.cusotmer = cusotmer; 
    } 
} 
関連する問題