Java 객체를 XML 문자열로 변환
예, 예 저는이 주제에 대해 많은 질문을 받았다는 것을 알고 있습니다. 그러나 여전히 내 문제에 대한 해결책을 찾을 수 없습니다. 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);
어떻게 할 수 있습니까?
Writer 를 매개 변수로 사용하는 마샬링에 마샬 러의 메서드를 사용할 수 있습니다 .
String 객체를 빌드 할 수있는 구현을 전달합니다.
직접 알려진 하위 클래스 : BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
toString 메서드를 호출 하여 실제 String 값을 가져옵니다.
그래서 :
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();
편리한 옵션은 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);
이 접근 방식에서는 확인 된 예외를 처리 할 필요가 없습니다.
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;
}
a에 마샬링 StringWriter
하고 문자열을 잡을 수 있습니다 . 에서 toString()
.
Java에서 객체를 XML로 변환하려면
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);
}
}
이 예제를 사용해보십시오 ..
Java 객체를 XML로 변환하기위한 Java 코드 테스트 및 작업 :
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);
}
}
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();
}
XML Stirng를 만드는 몇 가지 일반 코드
object --> is Java class to convert it to XML
name --> is just name space like thing - for differentiate
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;
}
I took the JAXB.marshal implementation and added jaxb.fragment=true to remove the XML prolog. This method can handle objects even without the XmlRootElement annotation. This also throws the unchecked 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);
}
}
If the compiler warning bothers you, here's the templated, two parameter version.
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);
}
}
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();
}
Use this function to convert Object to xml string (should be called as 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)
)
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;
}
참고URL : https://stackoverflow.com/questions/26959343/convert-java-object-to-xml-string
'Programing' 카테고리의 다른 글
빌드 서버에서 Visual Studio없이 ASP.NET 4.5 빌드 (0) | 2020.10.05 |
---|---|
.NET 메모리 부족 예외-1.3GB를 사용했지만 16GB가 설치되어 있습니다. (0) | 2020.10.05 |
Java Webservice Client (최상의 방법) (0) | 2020.10.05 |
아포스트로피가 리소스 번들에 배치 될 때 제대로 번역되지 않습니다. (0) | 2020.10.05 |
변수에 로컬 JSON 파일로드 (0) | 2020.10.05 |