代码格式 实体类
package com.jwttest.demo.toxml;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
@XmlRootElement(name="person") // 父节点名称
@XmlAccessorType(XmlAccessType.FIELD) //定义这个类中的何种类型需要映射到XML
public class Person {
@XmlElement(name = "name") // 子节点名称
public String name;
@XmlElementWrapper(name = "students") // 数组或集合节点名称
@XmlElement(name = "student")
public ArrayList<Student> arrayList;
public ArrayList<Student> getArrayList() {
return arrayList;
}
public void setArrayList(ArrayList<Student> arrayList) {
this.arrayList = arrayList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
--------------------------------------------------------------------------
package com.jwttest.demo.toxml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement(name="student")
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {
public Integer length;
public Integer high;
public Student(Integer length, Integer high) {
this.length = length;
this.high = high;
}
@Override
public String toString() {
return "Student{" +
"length=" + length +
", high=" + high +
'}';
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public Student() {
}
public Integer getHigh() {
return high;
}
public void setHigh(Integer high) {
this.high = high;
}
}
转化代码
package com.jwttest.demo.toxml;
import org.springframework.util.StringUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.PrintStream;
import java.io.StringWriter;
import java.util.ArrayList;
public class ToXml {
public static void main(String[] args) throws JAXBException {
Person person = new Person();
Student student = new Student(1,2);
Student student1 = new Student(3,4);
ArrayList<Student> students = new ArrayList<>();
person.setName("123");
students.add(student);
students.add(student1);
person.setArrayList(students);
String s = convertToXML(person);
System.out.println(s);
}
/**
* 将对象转为流程XML
*
* @param graphModel
* @return
* @throws JAXBException
*/
/**
* 将对象转为流程XML
*
* @param person
* @return
* @throws JAXBException
*/
public static String convertToXML(Person person) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
StringWriter writer = new StringWriter();
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(person, writer);
String xmlStr = writer.toString();
xmlStr = StringUtils.replace(xmlStr, """, "'");
return xmlStr;
}
}
转化后
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<name>123</name>
<students>
<student>
<length>1</length>
<high>2</high>
</student>
<student>
<length>3</length>
<high>4</high>
</student>
</students>
</person>
|