将 Java 对象转换为 XML 字符串 [英] Convert Java object to XML string

查看:74
本文介绍了将 Java 对象转换为 XML 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,是的,我知道有人问过很多关于这个话题的问题.但我仍然找不到解决我的问题的方法.我有一个带有属性注释的 Java 对象.例如客户,如本例中.我想要它的字符串表示.Google 建议将 JAXB 用于此类目的.但在所有示例中,创建的 XML 文件都会打印到文件或控制台,如下所示:

Yes, yes I know that lots of questions were asked about this topic. But I still cannot find the solution to my problem. I have a property annotated Java object. For example Customer, like in this example. And I want a String representation of it. Google reccomends using JAXB for such purposes. But in all examples created XML file is printed to file or console, like this:

File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);

但我必须使用这个对象并以 XML 格式通过网络发送.所以我想得到一个代表 XML 的字符串.

But I have to use this object and send over network in XML format. So I want to get a String which represents XML.

String xmlString = ...
sendOverNetwork(xmlString);

我该怎么做?

推荐答案

您可以使用 Marshaler 的方法进行封送处理,该方法需要 Writer 作为参数:

You can use the Marshaler's method for marshaling which takes a Writer as parameter:

元帅(对象,作家)

并传递给它一个可以构建字符串对象的实现

and pass it an Implementation which can build a String object

直接已知子类:BufferedWriter、CharArrayWriter、FilterWriter、OutputStreamWriter、PipedWriter、PrintWriter、StringWriter

Direct Known Subclasses: BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter

调用它的 toString 方法来获取实际字符串值.

Call its toString method to get the actual String value.

这样做:

StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();

这篇关于将 Java 对象转换为 XML 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆