gpt4 book ai didi

java - jaxb 以字符串形式输出

转载 作者:太空宇宙 更新时间:2023-11-04 12:39:02 24 4
gpt4 key购买 nike

我想在字符串类型容器中获取生成的 xml 输出,并进一步希望在控制台中显示该字符串。

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) {
}

最佳答案

你可以做到这一点...

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();
}

并在您想要执行的地方调用此方法:

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

关于java - jaxb 以字符串形式输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com