Convertir un objet Java en chaîne XML


Oui, oui je sais que beaucoup de questions ont été posées sur ce sujet. Mais je ne trouve toujours pas la solution à mon problème. J'ai une propriété annotée objet Java. Par exemple Client, comme dans cet exemple. Et je veux une représentation de chaîne de celui-ci. Google recommande d'utiliser JAXB à de telles fins. Mais dans tous les exemples, le fichier XML créé est imprimé dans un fichier ou une console, comme ceci:

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

Mais je dois utiliser cet objet et envoyer sur le réseau au format XML. Donc je veux obtenir un Chaîne qui représente XML.

String xmlString = ...
sendOverNetwork(xmlString);

Comment puis-je faire cela?

Author: Bob, 2014-11-16

10 answers

Vous pouvez utiliser le Marshaleur méthode de regroupement qui prend un Écrivain comme paramètre:

Maréchal(Objet,Écrivain)

Et lui passer une implémentation qui peut construire un objet String

Sous-classes connues directes: BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter

Appelez sa méthode toString pour obtenir la chaîne réelle valeur.

Ce faisant:

StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();
 77
Author: A4L, 2014-11-16 17:14:18

En mentionnant A4L, vous pouvez utiliser StringWriter. Fournir ici un exemple de code:

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;
}
 25
Author: Surendra, 2016-01-20 14:25:09

Une option pratique consiste à utiliser javax.XML.lier.JAXB :

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

Le processus inverse (unmarshal) serait:

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

Pas besoin de traiter les exceptions vérifiées dans cette approche.

 17
Author: juliaaano, 2017-05-12 12:45:08

Vous pouvez maréchal à un StringWriter et de saisir sa chaîne. de toString().

 5
Author: SLaks, 2014-11-16 16:43:01

Pour convertir un Objet XML en Java

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

}

Essayez avec cet exemple..

 2
Author: Abu Bakar Siddik, 2016-05-03 11:25:24

Tester et travailler le code Java pour convertir l'objet java en XML:

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

}
 1
Author: Rahul Raina, 2016-04-27 07:17:49

Utilisation de 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
Author: Sireesh Yarlagadda, 2016-06-23 21:31:13

Un code générique pour créer XML Stirng

object> > est une classe Java pour la convertir en XML
name > > est juste un espace de nom comme thing-pour différencier

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
Author: Krishna, 2018-09-12 08:53:10
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
Author: Abhay Gupta, 2017-01-25 15:02:02

Utilisez cette fonction pour convertir un objet en chaîne xml (devrait être appelé comme convertToXml (sourceObject, Object.classe); )-->

Importer javax.XML.lier.JAXBContext;

Importer javax.XML.lier.JAXBElement;

Importer javax.XML.lier.JAXBException;

Importer javax.XML.lier.Marshaller;

Importer javax.XML.lier.Unmarshaller;

Importer javax.XML.espace de noms.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;
}

Utilisez cette fonction pour convertir une chaîne xml en objet back> (doit être appelé comme createObjectFromXmlString(xmlString, objet.classe))

Public static T createObjectFromXmlString(Chaîne xml, Classe clazz) jette 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;
}
 -1
Author: K. Soni, 2017-04-20 09:11:08