Converter objecto Java para texto 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);
Mas tenho de usar este objecto e enviar a rede em formato XML. Então eu quero obtenha um texto que represente XML.
String xmlString = ...
sendOverNetwork(xmlString);
Como posso fazer isto?
10 answers
Você pode usar o método do Marshaler para marshaling que toma um escritor como parâmetro:
E passar-lhe uma implementação que pode construir um objecto de texto
Subclasses Directamente Conhecidos: BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
Chama o seu método toString para obter a cadeia de caracteres actual valor.
Assim fazendo:
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();
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;
}
Uma opção conveniente é usar javax.xml.vincular.JAXB:
StringWriter sw = new StringWriter();
JAXB.marshal(customer, sw);
String xmlString = sw.toString();
O processo inverso (unmarshal) seria:
Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);
Não é necessário tratar das excepções verificadas nesta abordagem.
StringWriter
e agarra-lhe o fio. de toString()
.
Para converter um objecto para XML em Java
Cliente.javapackage 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);
}
}
Tente com este exemplo..
Testar e trabalhar o código Java para converter o objecto java em XML:
Cliente.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);
}
}
Usando O 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();
}
Algum código genérico para criar XML Stirng
o objecto --> é a classe Java para o converter para XML
o nome -- > é apenas espaço de nome como algo-para diferenciar
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;
}
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();
}
Utilize esta função para converter o objecto para texto xml (should be called as convertToXml (sourceObject, Object.classe); )-->
Importar javax.xml.vincular.JAXBContext;
Importar javax.xml.vincular.JAXBElement;
Importar javax.xml.vincular.Jaxbexcepção;
Importar javax.xml.vincular.Marshaller;
Importar javax.xml.vincular.Unmarshaller;
Importar javax.xml.espaco.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 esta função para converter o texto xml para o objecto de volta --> (deve ser chamado como createObjectFromXmlString (xmlString, Object.classe)
Public static t createObjectFromXmlString (String xml, Class clazz) lança 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;
}