将Java对象转换为XML字符串


91

是的,是的,我知道有关此主题的问题很多。但是我仍然找不到解决我问题的方法。我有一个带属性的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);

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

String xmlString = ...
sendOverNetwork(xmlString);

我怎样才能做到这一点?

Answers:


111

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

元帅(Object,Writer)

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

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

调用其toString方法以获取实际的String值。

这样做:

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

4
StringWriter很老 在幕后,它使用StringBuffer了本来可以使用更快的方法的方法,StringBuilder但是当StringWriter首次制作时,这种方法就不存在了。因此,每次调用都sw.toString()意味着同步。如果您正在寻找性能,那就不好了。
peterh 2016年

2
@peterh这里的所有答案都使用StringWriter。您会建议什么呢?
Christopher Schneider

1
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE); 使用它来获取XML的确切结构。
达斯·普拉卡什

36

一个方便的选择是使用javax.xml.bind.JAXB

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

反向过程(取消调度)将是:

Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);

这种方法无需处理检查的异常。


这不会复制只有吸气剂的字段
gyosifov

30

正如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;
}

不需要使用StringWriter m.marshal(customer,System.out);
德米特里Gr

6

您可以将其编组为a StringWriter并获取其字符串。来自toString()


@KickButtowski:答案的关键部分就是使用StringWriter。链接只是文档。
SLaks

请添加一些解释,很高兴我删除我的不赞成投票。:)在旁边,您可以发表评论
Kick Buttowski

您能提供一个示例用法吗?
鲍勃

@Bob:创建一个StringWriter,并将其传递给marshal()call toString()
SLaks 2014年

2
@Bob这个答案实际上是足够的。请学习如何研究API,在此示例中,Marshaller有几种方法调度的重载方法,只需查看它们的参数以及它们的作用,即可找到答案。
A4L

2

测试并将Java对象转换为XML的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

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

}

通常,添加仅包含代码且没有任何解释的答案的想法是不对的
福特

2

在Java中将对象转换为XML

客户.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

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

}

尝试使用此示例。


1

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

1

我采用了JAXB.marshal实现,并添加了jaxb.fragment = true来删除XML序言。即使没有XmlRootElement批注,此方法也可以处理对象。这也会引发未经检查的DataBindingException。

public static String toXmlString(Object o) {
    try {
        Class<?> clazz = o.getClass();
        JAXBContext context = JAXBContext.newInstance(clazz);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // remove xml prolog
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // formatted output

        final QName name = new QName(Introspector.decapitalize(clazz.getSimpleName()));
        JAXBElement jaxbElement = new JAXBElement(name, clazz, o);

        StringWriter sw = new StringWriter();
        marshaller.marshal(jaxbElement, sw);
        return sw.toString();

    } catch (JAXBException e) {
        throw new DataBindingException(e);
    }
}

如果编译器警告您,请使用模板化的两个参数版本。

public static <T> String toXmlString(T o, Class<T> clazz) {
    try {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // remove xml prolog
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // formatted output

        QName name = new QName(Introspector.decapitalize(clazz.getSimpleName()));
        JAXBElement jaxbElement = new JAXBElement<>(name, clazz, o);

        StringWriter sw = new StringWriter();
        marshaller.marshal(jaxbElement, sw);
        return sw.toString();

    } catch (JAXBException e) {
        throw new DataBindingException(e);
    }
}

0

一些通用代码来创建XML Stirng

对象->是将其转换为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;
    }

0

这是用于封送和拆封对象的util类。在我的情况下,这是一个嵌套类,因此我将其设置为静态JAXBUtils。

import javax.xml.bind.JAXB;
import java.io.StringReader;
import java.io.StringWriter;

public class JAXBUtils
{
    /**
     * Unmarshal an XML string
     * @param xml     The XML string
     * @param type    The JAXB class type.
     * @return The unmarshalled object.
     */
    public <T> T unmarshal(String xml, Class<T> type)
    {
        StringReader reader = new StringReader(xml);
        return javax.xml.bind.JAXB.unmarshal(reader, type);
    }

    /**
     * Marshal an Object to XML.
     * @param object    The object to marshal.
     * @return The XML string representation of the object.
     */
    public String marshal(Object object)
    {
        StringWriter stringWriter = new StringWriter();
        JAXB.marshal(object, stringWriter);
        return stringWriter.toString();
    }
}

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

-1

使用此函数将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;
}

使用此函数将xml字符串转换为Object back->(应称为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 using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.