Konwertuj obiekt Java na ciąg XML


92

Tak, tak, wiem, że zadawano wiele pytań na ten temat. Ale nadal nie mogę znaleźć rozwiązania mojego problemu. Mam obiekt Java z adnotacjami. Na przykład Klient, jak w tym przykładzie . Chcę, żeby to było w postaci String. Google zaleca używanie JAXB do takich celów. Ale we wszystkich przykładach utworzony plik XML jest drukowany do pliku lub konsoli, na przykład:

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

Ale muszę użyć tego obiektu i wysłać przez sieć w formacie XML. Więc chcę uzyskać String, który reprezentuje XML.

String xmlString = ...
sendOverNetwork(xmlString);

Jak mogę to zrobić?

Odpowiedzi:


113

Możesz użyć metody Marshalera do organizowania, która przyjmuje Writer jako parametr:

marszałek (obiekt, pisarz)

i przekaż mu implementację, która może zbudować obiekt String

Znane bezpośrednio podklasy: BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter

Wywołaj jego metodę toString , aby uzyskać rzeczywistą wartość String.

Tak więc:

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

4
StringWriterjest bardzo stary. Pod okładkami używa StringBuffertam, gdzie byłoby znacznie szybsze podejście, StringBuilderale nie istniało, gdy po raz pierwszy powstał StringWriter. Z tego powodu każde wywołanie sw.toString()oznacza synchronizację. Źle, jeśli szukasz wydajności.
peterh

2
@peterh Wszystkie odpowiedzi tutaj używają StringWriter. Co byś zaproponował zamiast tego?
Christopher Schneider,

1
jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); Użyj tego, aby uzyskać dokładną strukturę XML.
Das Prakash

37

Wygodną opcją jest użycie javax.xml.bind.JAXB :

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

Odwrotny proces (nieistotny) wyglądałby tak:

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

W tym podejściu nie ma potrzeby zajmowania się zaznaczonymi wyjątkami.


To nie skopiuje pól, które mają tylko
gettery

30

Jak wspomina A4L, możesz użyć StringWriter. Podając tutaj przykładowy kod:

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

nie ma potrzeby w StringWriter m.marshal (klient, System.out);
Dmitry Gr

6

Możesz zebrać go StringWriteri złapać za sznurek. od toString().


@KickButtowski: Zasadniczą częścią odpowiedzi jest użycie pliku StringWriter. Link to tylko dokumentacja.
SLaks

proszę o wyjaśnienie i chętnie wycofuję swój głos negatywny. :) obok można to zamieścić jako komentarz
Kick Buttowski

Czy możesz podać przykład jego użycia?
Bob

@Bob: Utwórz StringWriter, przekaż to marshal(), zadzwoń toString().
SLaks

2
@Bob, ta odpowiedź jest właściwie wystarczająca. Dowiedz się, jak badać interfejsy API, w tym przykładzie Marshallerma kilka przeciążonych metod organizatora, po prostu spójrz na ich parametry i do czego służą, a znajdziesz odpowiedź.
A4L

3

Aby przekonwertować obiekt na XML w Javie

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

}

Spróbuj na tym przykładzie ..


2

Testowanie i działający kod Java do konwersji obiektu java na XML:

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

}

Generalnie dodawanie odpowiedzi, które zawierają tylko kod i bez wyjaśnienia, nie są mile widziane
ford prefect

1

Korzystanie z 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

Wziąłem implementację JAXB.marshal i dodałem jaxb.fragment = true, aby usunąć prolog XML. Ta metoda może obsługiwać obiekty nawet bez adnotacji XmlRootElement. Spowoduje to również zgłoszenie niesprawdzonego 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);
    }
}

Jeśli przeszkadza Ci ostrzeżenie kompilatora, oto wersja szablonu z dwoma parametrami.

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

Trochę kodu ogólnego do tworzenia mieszania XML

obiekt -> to klasa Javy do konwersji na nazwę XML
-> to po prostu przestrzeń nazw podobna do rzeczy - dla rozróżnienia

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

Oto klasa utylizacji służąca do organizowania i wycofywania obiektów. W moim przypadku była to klasa zagnieżdżona, więc uczyniłem ją statyczną 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

Użyj tej funkcji, aby przekonwertować obiekt na ciąg xml (powinien się nazywać 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;
}

Użyj tej funkcji, aby przekonwertować ciąg xml na Object z powrotem -> (należy wywołać jako 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;
}
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.