2016-05-04 118 views
1

我想讓我生成的xml輸出字符串類型的容器,並進一步要在控制檯中顯示該字符串。在字符串jaxb輸出

try { 

      file = new File(XMLName); 
      JAXBContext jaxbContext = JAXBContext 
        .newInstance(ActivityXmlV1.class); 
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); 
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
      jaxbMarshaller.marshal(activityXmlV1, file); 
      //jaxbMarshaller.marshal(activityXmlV1, System.out); 
      xmlData=asString(jaxbContext, activityXmlV1); 
      System.out.println(xmlData); 
      System.out.println("Sucess!!"); 
     } catch (UnmarshalException ue) { 
     } catch (Exception e) { 
    } 

回答

0

你可以做到這一點...

public String asString(JAXBContext pContext, Object pObject)throws JAXBException { 
     java.io.StringWriter sw = new StringWriter(); 
     Marshaller marshaller = pContext.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); 
     marshaller.marshal(pObject, sw); 
     return sw.toString(); 
    } 

,並調用該方法,其中u希望通過牛逼執行:

System.out.println(asString(jaxbContext,activityXmlV1));