попробуйте следующее решение,
сначала прочитайте файл csv и соберите объекты (персона) из отдельных строк. затем упорядочить список объектов в xml file
People. java (root элемент xml file)
@XmlRootElement(name="people")
@XmlAccessorType (XmlAccessType.FIELD)
public class People {
@XmlElement(name="person")
private List<Person> listPerson;
public List<Person> getListPerson() {
return listPerson;
}
public void setListPerson(List<Person> listPerson) {
this.listPerson = listPerson;
}
}
Person. java (дочерние элементы родительского элемента (людей)
@XmlRootElement(name="person")
@XmlAccessorType (XmlAccessType.FIELD)
public class Person {
private String id;
private String firstName;
private String lastName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
маршалинг с выводом java
public class Marshaller {
public static void main(String[] args) {
BufferedReader br;
String line;
People people = new People();
ArrayList<Person> list = new ArrayList();
//read the csv file and collect the person objects
try {
br = new BufferedReader(new FileReader("inputCSV.csv"));
while ((line = br.readLine()) != null) { //get every single line individually in csv file
String[] value = line.split(","); //collect the comma separated values into array
Person person = new Person();
person.setId(value[0]); //first element of an array is id
person.setFirstName(value[1]); //second element of an array is firstName
person.setLastName(value[2]); //third element of an array is lastName
list.add(person); //add person object into the list
}
} catch (IOException e) {
e.printStackTrace();
}
people.setListPerson(list); //set person object list to people
people.getListPerson().remove(0); //remove the first person object of list. because it holds the column's names
//marshaling with java
try {
JAXBContext jaxbContext = JAXBContext.newInstance(People.class);
javax.xml.bind.Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(people, new File("output.xml"));
jaxbMarshaller.marshal(people, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
inputCSV.csv
id,firstname,Lastname
1,yong,mook kim
2, Alez, Aunritod
. xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<people>
<person>
<id>1</id>
<firstName>yong</firstName>
<lastName>mook kim</lastName>
</person>
<person>
<id>2</id>
<firstName> Alez</firstName>
<lastName> Aunritod</lastName>
</person>
</people>