将Java对象转换为XML字符串 [英] Convert Java object to XML string
问题描述
是的,我知道有很多关于这个话题的问题。但我仍然无法找到解决问题的方法。我有一个属性注释的Java对象。例如,客户,在此示例中。我想要一个String表示它。谷歌建议将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的String。
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:
并传递一个可以构建String对象的实现
and pass it an Implementation which can build a String object
直接已知子类:
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屋!