2014-10-02 77 views
6

當我運行編組操作我得到以下錯誤:與JAXB,元帥,問題 - 不能編組類型「java.lang.String中」

javax.xml.bind.MarshalException 
- with linked exception: 
[com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an @XmlRootElement annotation] 
    ... 

Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an @XmlRootElement annotation 
    at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:237) 
    at com.sun.xml.internal.bind.v2.runtime.LeafBeanInfoImpl.serializeRoot(LeafBeanInfoImpl.java:126) 
    at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:483) 
    at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308) 
    ... 6 more 

這是我編組站......

功能
public StringBuffer Marshaller(Object marshall){ // make marshalling->Java to XML 
     StringWriter writer = new StringWriter(); 
     try { 
      JAXBContext jaxbContext=JAXBContext.newInstance(marshall.getClass()); 
      Marshaller jaxbMarshaller=jaxbContext.createMarshaller(); 
      // çıktı 
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
      jaxbMarshaller.marshal(marshall, writer); 
      System.out.println(writer.getBuffer().toString()); 
     } catch (PropertyException e) { 
      e.printStackTrace(); 
     } catch (JAXBException e) { 
      e.printStackTrace(); 
     } 
     return writer.getBuffer(); 

    } 

感謝您的利益..

回答

9

你不能名帥只是一個String,因爲它沒有任何根元素信息(因此關於失蹤異常3210註釋),但您可以將其包裝在JAXBElement的實例中,然後編組。 JAXBElement是將此根元素信息提供給JAXB的另一種方法。

創建JAXBElement

JAXBElement<String> jaxbElement = 
    new JAXBElement(new QName("root-element"), 
    String.class, string); 

如果您生成模式從XML模式

如果從XML架構中創建對象模型的實例。並且您有一個頂級XML元素,其數據類型爲xs:string,那麼將在生成的ObjectFactory類中提供一種便捷方法,該類將幫助您創建JAXBElement實例。

+0

你能解釋一下嗎? – 2014-10-02 18:25:16

+0

@nurdankaraman - 我已經添加了一些額外的信息給我的答案。 – 2014-10-02 18:56:57

+0

非常感謝你:) – 2014-10-03 06:15:36