I have to create an XML file from java object with specific format of my XML file.
My xml should look like this.
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person
name="Nick"
birthday = "09.03.1814"/>
</persons>
Or like this one.
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person surname="Sd" name="aaa" birthday = "09.03.1814"/>
</persons>
Depends on old format of xml. How could i do this? Thanks!
I've try to use this code for creating xml
public static void createNewXml(List<Person> persons) {
List<DtoPerson> dtoPersonList = new ArrayList<>();
for (Person person : persons) {
dtoPersonList.add(new DtoPerson(person));
}
try {
JAXBContext jaxbContext = JAXBContext.newInstance(DtoPerson.class);
Marshaller marshaller = jaxbContext.createMarshaller();
File file = new File("personx.xml");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
for(DtoPerson personDto : dtoPersonList) {
marshaller.marshal(personDto, file);
}
} catch (JAXBException e) {
throw new RuntimeException(e);
}
System.out.println(Arrays.toString(dtoPersonList.toArray()));
}
But this code create an xml with other format
<dtoPerson>
<birthday>09.03.1814</birthday>
<name>aaa Sd</name>
</dtoPerson>
CodePudding user response:
You need to add annotation @XmlAttribute to affected fields in DtoPerson.