2012-02-05 66 views
25
JAXBContext context = JAXBContext 
        .newInstance(CreateExemptionCertificate.class); 
      Marshaller m = context.createMarshaller(); 
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 

      m.marshal(cc, System.out); 

在上面的代碼中,我得到了控制檯的結果(我的意思是XML打印在控制檯上)。我想讓這個XML到一個字符串。我沒有得到哪個參數,我應該傳遞給編組方法來獲取XML字符串中的字符串變量,而不是將其打印在控制檯上。任何人有任何想法,請分享。將馬歇爾結果寫入字符串

+0

的[I要轉換的輸出流入字符串對象]可以重複(http://stackoverflow.com/questions/2472155/i-want-to-convert-an- output-stream-into-string-object) – nbrooks 2015-02-25 18:30:59

回答

5

嘗試對編號爲ByteArrayOutputStream的實例進行編組,然後在其上調用toByteArray

+0

你想用它做什麼?我提出的方法(在流上調用'toByteArray()')會給你一個包含XML字節的byte []'實例。 – laz 2012-02-06 06:08:33

+0

我有相同的需求,在我的情況下,我試圖返回它作爲服務調用的結果。 – 2013-11-10 21:09:21

11

你可以像下面這樣做:

CreateExemptionCertificate cc = ...; 
    JAXBContext context = JAXBContext.newInstance(CreateExemptionCertificate.class); 
    Marshaller m = context.createMarshaller(); 
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 

    StringWriter sw = new StringWriter(); 
    m.marshal(cc, sw); 

    String result = sw.toString();