这也是我所做的,它对我有用。举个例子,希望对你有帮助:
MarshallerTest.java:
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
public class MarshallerTest {
public static void main(String[] args) throws IOException, MappingException, MarshalException, ValidationException {
Mapping mapping = new Mapping();
mapping.loadMapping(MarshallerTest.class.getResource("/mapping.xml"));
StringWriter sw = new StringWriter();
Marshaller marshaller = new Marshaller(sw);
marshaller.setMapping(mapping);
marshaller.setSuppressNamespaces(true);
marshaller.setSuppressXSIType(true);
Person alex = new Person();
alex.setName("alex");
alex.setHobbies(Arrays.asList(new String[]{"fishing", "hiking"}));
marshaller.marshal(alex);
System.out.println(sw.toString());
}
}
人.java:
public class Person {
private String name;
private List<String> hobbies;
// ...getters and setters
}
castor.properties
org.exolab.castor.indent=true
输出:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<hobbies>fishing</hobbies>
<hobbies>hiking</hobbies>
<name>alex</name>
</person>