Issue
I'm using spring batch to generate xml files.
My writer looks like :
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
StaxEventItemWriter<Person> itemWriter = new StaxEventItemWriter<>();
itemWriter.setRootTagName("Persons");
itemWriter.setMarshaller(marshaller);
itemWriter.setRootElementAttributes(new HashMap<String, String>() {{
put("xmlns", "http://entreprise.uk/ns");
}});
itemWriter.setResource(new FileSystemResource(Paths.get("personOutput.xml").toFile()));
itemWriter.afterPropertiesSet();
return itemWriter;
And the person class :
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Person")
public class Person {
//...
}
When I run the batch I get this error :
Caused by: javax.xml.stream.XMLStreamException: xmlns has been already bound to . Rebinding it to http://entreprise.uk/ns is an error
Anyone knows how to fix it ? I need to see xmlns attribut at the root element like :
<?xml version="1.0" encoding="UTF-8"?>
<Persons xmlns="http://entreprise.uk/ns">
<person>...</person>
</Persons>
I'm using spring-boot-starter-batch:2.3.5.RELEASE
Solution
To add namespace at the root level, you have to modify the rootTagName in your configuration.
rootTagName("{http://entreprise.uk/ns}Persons")
Hope this solves your problem.
Answered By - truekiller
Answer Checked By - David Goodson (JavaFixing Volunteer)