将 Java 对象转换为 XML 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26959343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Java object to XML string
提问by Bob
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:
是的,是的,我知道有很多关于这个话题的问题。但我仍然找不到解决我的问题的方法。我有一个带有属性注释的 Java 对象。例如客户,就像在这个例子中一样。我想要它的字符串表示。Google 建议将 JAXB 用于此类目的。但在所有示例中,创建的 XML 文件都会打印到文件或控制台,如下所示:
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);
But I have to use this object and send over network in XML format. So I want to get a String which represents XML.
但我必须使用这个对象并以 XML 格式通过网络发送。所以我想得到一个代表 XML 的字符串。
String xmlString = ...
sendOverNetwork(xmlString);
How can I do this?
我怎样才能做到这一点?
采纳答案by A4L
You can use the Marshaler's method for marshaling which takes a Writeras parameter:
您可以使用 Marshaler 的方法进行封送处理,该方法以Writer作为参数:
and pass it an Implementation which can build a String object
并传递一个可以构建 String 对象的实现
Direct Known Subclasses:BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
直接已知子类:BufferedWriter、CharArrayWriter、FilterWriter、OutputStreamWriter、PipedWriter、PrintWriter、StringWriter
Call its toStringmethod to get the actual String value.
调用它的toString方法来获取实际的 String 值。
So doing:
这样做:
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();
回答by SLaks
You can marshal it to a StringWriter
and grab its string. from toString()
.
你可以将它编组到 aStringWriter
并抓住它的字符串。从toString()
.
回答by Surendra
As A4L mentioning, you can use StringWriter. Providing here example code:
正如 A4L 所提到的,您可以使用 StringWriter。在此处提供示例代码:
private static String jaxbObjectToXML(Customer customer) {
String xmlString = "";
try {
JAXBContext context = JAXBContext.newInstance(Customer.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML
StringWriter sw = new StringWriter();
m.marshal(customer, sw);
xmlString = sw.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlString;
}
回答by Rahul Raina
Testing And working Java code to convert java object to XML:
将 Java 对象转换为 XML 的测试和工作 Java 代码:
Customer.java
客户.java
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
int id;
String desc;
ArrayList<String> list;
public ArrayList<String> getList()
{
return list;
}
@XmlElement
public void setList(ArrayList<String> list)
{
this.list = list;
}
public String getDesc()
{
return desc;
}
@XmlElement
public void setDesc(String desc)
{
this.desc = desc;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
createXML.java
创建XML文件
import java.io.StringWriter;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class createXML {
public static void main(String args[]) throws Exception
{
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
Customer c = new Customer();
c.setAge(45);
c.setDesc("some desc ");
c.setId(23);
c.setList(list);
c.setName("name");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(c, sw);
String xmlString = sw.toString();
System.out.println(xmlString);
}
}
回答by Abu Bakar Siddik
To convert an Object to XML in Java
在 Java 中将对象转换为 XML
Customer.java
客户.java
package com;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author ABsiddik
*/
@XmlRootElement
public class Customer {
int id;
String name;
int age;
String address;
ArrayList<String> mobileNo;
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
@XmlElement
public void setAddress(String address) {
this.address = address;
}
public ArrayList<String> getMobileNo() {
return mobileNo;
}
@XmlElement
public void setMobileNo(ArrayList<String> mobileNo) {
this.mobileNo = mobileNo;
}
}
ConvertObjToXML.java
ConvertObjToXML.java
package com;
import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
/**
*
* @author ABsiddik
*/
public class ConvertObjToXML {
public static void main(String args[]) throws Exception
{
ArrayList<String> numberList = new ArrayList<>();
numberList.add("01942652579");
numberList.add("01762752801");
numberList.add("8800545");
Customer c = new Customer();
c.setId(23);
c.setName("Abu Bakar Siddik");
c.setAge(45);
c.setAddress("Dhaka, Bangladesh");
c.setMobileNo(numberList);
File file = new File("C:\Users\NETIZEN-ONE\Desktop \customer.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(c, file);// this line create customer.xml file in specified path.
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(c, sw);
String xmlString = sw.toString();
System.out.println(xmlString);
}
}
Try with this example..
试试这个例子..
回答by Sireesh Yarlagadda
Using ByteArrayOutputStream
使用 ByteArrayOutputStream
public static String printObjectToXML(final Object object) throws TransformerFactoryConfigurationError,
TransformerConfigurationException, SOAPException, TransformerException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLEncoder xmlEncoder = new XMLEncoder(baos);
xmlEncoder.writeObject(object);
xmlEncoder.close();
String xml = baos.toString();
System.out.println(xml);
return xml.toString();
}
回答by Abhay Gupta
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
private String generateXml(Object obj, Class objClass) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(objClass);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(obj, sw);
return sw.toString();
}
回答by juliaaano
A convenient option is to use javax.xml.bind.JAXB:
一个方便的选择是使用javax.xml.bind.JAXB:
StringWriter sw = new StringWriter();
JAXB.marshal(customer, sw);
String xmlString = sw.toString();
The reverse process (unmarshal) would be:
反向过程(解组)将是:
Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);
No need to deal with checked exceptions in this approach.
这种方法不需要处理检查异常。
回答by K. Soni
Use this function to convert Object to xml string (should be called as convertToXml(sourceObject, Object.class); )-->
使用这个函数将Object转换成xml字符串(应该叫convertToXml(sourceObject, Object.class);)-->
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
public static <T> String convertToXml(T source, Class<T> clazz) throws JAXBException {
String result;
StringWriter sw = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
QName qName = new QName(StringUtils.uncapitalize(clazz.getSimpleName()));
JAXBElement<T> root = new JAXBElement<T>(qName, clazz, source);
jaxbMarshaller.marshal(root, sw);
result = sw.toString();
return result;
}
Use this function to convert xml string to Object back -->
(should be called as createObjectFromXmlString(xmlString, Object.class)
)
使用该函数将xml字符串转回Object-->(应调用为createObjectFromXmlString(xmlString, Object.class)
)
public static <T> T createObjectFromXmlString(String xml, Class<T> clazz) throws JAXBException, IOException{
T value = null;
StringReader reader = new StringReader(xml);
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<T> rootElement=jaxbUnmarshaller.unmarshal(new StreamSource(reader),clazz);
value = rootElement.getValue();
return value;
}
回答by Vasudeva Krishnan
Some Generic code to create XML Stirng
创建 XML 搅拌的一些通用代码
object --> is Java class to convert it to XML
name --> is just name space like thing - for differentiate
object --> 是将其转换为 XML名称的Java 类
--> 只是名称空间之类的东西 - 用于区分
public static String convertObjectToXML(Object object,String name) {
try {
StringWriter stringWriter = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
QName qName = new QName(object.getClass().toString(), name);
Object root = new JAXBElement<Object>(qName,java.lang.Object.class, object);
jaxbMarshaller.marshal(root, stringWriter);
String result = stringWriter.toString();
System.out.println(result);
return result;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}