将XML转换为字符串JAVA

时间:2018-01-14 12:44:23

标签: java xml string

我有这个方法:

public StampaModuloPrivacyResponse generaXmlALC(StampaModuloPrivacyRequest input)
        {  
        final StampaModuloPrivacyResponse stampaModuloPrivacyResponse = new StampaModuloPrivacyResponse();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(StampaModuloPrivacyRequest.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(input, System.out);
            /*HERE*/
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return stampaModuloPrivacyResponse;
    } 
}

我需要在字符串中转换从marshaller返回的xml,因为我必须在stampamoduloPrivacyResponse.setXMLString()中设置...我该怎么办? 感谢

2 个答案:

答案 0 :(得分:1)

这里:

jaxbMarshaller.marshal(input, System.out);

您使用接受输出流的marshal(Object jaxbElement, java.io.OutputStream os )方法并在标准输出中编写xml内容。
你不希望这样。

Marshaller.marshal()已超载且版本接受Writer

您可以StringWriter使用Writer

StringWriter writer = new StringWriter();
jaxbMarshaller.marshal(input, writer);
String xmlString = writer.toString();

答案 1 :(得分:0)

使用StringWriter:

StringWriter out = new StringWriter();
jaxbMarshaller.marshal(input, out);
stampamoduloPrivacyResponse.setXMLString(out.toString());