it-source

Java 개체를 XML 문자열로 변환

criticalcode 2022. 11. 1. 00:00
반응형

Java 개체를 XML 문자열로 변환

네, 네, 저는 이 주제에 대해 많은 질문을 받은 것을 알고 있습니다.하지만 나는 여전히 내 문제에 대한 해결책을 찾을 수 없다.속성 주석이 달린 Java 개체가 있습니다.를 들어, 이 예시와 같이 Customer를 선택합니다.그리고 나는 그것의 String 표현을 원한다.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을 받고 싶습니다.

String xmlString = ...
sendOverNetwork(xmlString);

이거 어떻게 해?

Writer를 매개 변수로 사용하는 Marshaling에 Marsheler 메서드를 사용할 수 있습니다.

marshal(오브젝트, 라이터)

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

[(reverse)]프로세스(비마찬가지)는 다음과 같습니다.

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

에 정렬하여 문자열을 가져올 수 있습니다.부터toString().

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

}

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

}

이 예에서 시도해 보십시오.

오브젝트 마샬링 및 마샬링 해제에 대한 util 클래스입니다.내 경우 네스트 클래스였기 때문에 정적 JAX로 했습니다.부틸스

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

Byte Array Output Stream 사용

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

JAXB.marshal 구현을 사용하여 jaxb.marshal=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);
    }
}

컴파일러의 경고가 마음에 걸리는 경우는, 2개의 파라메타 버전이 있습니다.

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

다음은 Java 클래스의 한 가지 예입니다. XML을 생성하기 위한 다른 주석 집합, XML을 생성하기 위한 CDATA 및 JaxB 코드입니다.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="customer")
public class Customer {
   
   @XmlElement(name = "first-name")
   String firstName;
   @XmlElement(name = "last-name")
   String lastName;
   
   @XmlElement(name= "customer-address")
   private Address address;
   
   @XmlElement(name= "bio")
   @XmlJavaTypeAdapter(AdapterCDATA.class)
   private Biography bio;
}


@XmlAccessorType(XmlAccessType.FIELD)
public class Address {
   
   @XmlElement(name = "house-number")
   String houseNumber;
   @XmlElement(name = "address-line-1")
   String addLine1;
   
   @XmlElement(name = "address-line-2")
   String addLine2;
   
  }

 

어댑터 클래스

    public class AdaptorCDATA extends XmlAdapter<String, String> {

    @Override
    public String marshal(String arg0) throws Exception {
        return "<![CDATA[" + arg0 + "]]>";
    }
    @Override
    public String unmarshal(String arg0) throws Exception {
        return arg0;
    }
}

XML을 생성하기 위한 JAXB 코드

  public String xmlStringForCustomer(Customer customer) {
 
   JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    
    StringWriter writer = new StringWriter();
    marshaller.marshal(customer,sw);
    return sw.toString();
}

위 코드는 다음과 같은 xml을 생성합니다.

<customer>
 <first-name></first-name>
 <last-name></last-name>
 <customer-address> 
     <house-number></house-number>
     <address-line-1></address-line-1>
     <address-line-2></address-line-2>
 </customer-address>
 <bio>
   <![CDATA[ **bio data will come here**]]>
 </bio>
< /customer>

XML Stirng을 만들기 위한 일부 일반 코드

object -->는 XML로 변환하기 위한 Java 클래스입니다.
name -->는 이름공간과 같은 것입니다.구분하기 위해서입니다.

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

언더스코어 자바는 빌더의 도움을 받아 XML 문자열을 작성할 수 있습니다.

    class Customer {
        String name;
        int age;
        int id;
    }
    Customer customer = new Customer();
    customer.name = "John";
    customer.age = 30;
    customer.id = 12345;

    String xml = U.objectBuilder().add("customer", U.objectBuilder()
        .add("name", customer.name)
        .add("age", customer.age)
        .add("id", customer.id)).toXml();

    // <?xml version="1.0" encoding="UTF-8"?>
    //    <customer>
    //      <name>John</name>
    //      <age number="true">30</age>
    //      <id number="true">12345</id>
    //    </customer>
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();
    }

개체를 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 문자열을 오브젝트백 -->으로 변환합니다(이 함수는 다음과 같습니다).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

반응형