Java:将List对象序列化为XML
在Java中将一个List对象转换成XML格式通常需要使用一些额外的库比如JAXBJava Architecture for XML Binding或者更现代的库如Jackson或XStream。下面我将分别介绍如何使用这三种方法来将List对象输出为XML。使用JAXB1. 添加依赖首先确保项目中加入了JAXB的依赖。如果你使用Maven可以在pom.xml中添加如下依赖dependencygroupIdjavax.xml.bind/groupIdartifactIdjaxb-api/artifactIdversion2.3.1/version/dependency2. 定义一个类与List的映射创建一个类该类与List中的对象相对应。例如如果List包含Person对象需要先定义一个Person类。import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlElement;import java.util.List;XmlRootElement(name persons)public class Persons {XmlElement(name person)private ListPerson personList;public ListPerson getPersonList() {return personList;}public void setPersonList(ListPerson personList) {this.personList personList;}}import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;XmlRootElement(name person)public class Person {private String name;private int age;public Person() {}public Person(String name, int age) {this.name name;this.age age;}XmlAttributepublic String getName() {return name;}public void setName(String name) {this.name name;}XmlAttributepublic int getAge() {return age;}public void setAge(int age) {this.age age;}}3. 序列化List为XML使用JAXBContext和Marshaller来序列化你的List。import javax.xml.bind.JAXBContext;import javax.xml.bind.Marshaller;import java.io.StringWriter;import java.util.Arrays;import java.util.List;public class ListToXmlExample {public static void main(String[] args) throws Exception {ListPerson personList Arrays.asList(new Person(Alice, 30), new Person(Bob, 25));Persons persons new Persons();persons.setPersonList(personList);JAXBContext context JAXBContext.newInstance(Persons.class);Marshaller marshaller context.createMarshaller();marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // 格式化输出使XML更易读StringWriter writer new StringWriter();marshaller.marshal(persons, writer); // 序列化到StringWriter你也可以序列化到文件等。System.out.println(writer.toString()); // 打印或使用XML字符串。}}这段代码会输出一个格式化的XML字符串表示personList的内容。
