When trying to output indented XML using the JAXB implementation of the JDK (implementation built into the JDK up to JDK 10 = com.sun.xml.bind: jaxb-impl
), the indent is a half-width space by default. It will be 4 characters.
model
@XmlRootElement
public class User {
private String id;
private String name;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
XML output processing using JAXB
User user = new User();
user.setId("001");
user.setName("Kazuki");
Marshaller marshaller = JAXBContext.newInstance(User.class).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(user, writer);
System.out.println(writer.toString());
Output XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<id>001</id>
<name>Kazuki</name>
</user>
When using the JAXB implementation of the JDK, you can specify an indent string in the com.sun.xml.internal.bind.indentString
property.
Indent character string specification example
User user = new User();
user.setId("001");
user.setName("Kazuki");
Marshaller marshaller = JAXBContext.newInstance(User.class).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("com.sun.xml.internal.bind.indentString", " "); //2 single-byte spaces
StringWriter writer = new StringWriter();
marshaller.marshal(user, writer);
System.out.println(writer.toString());
Output XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
<id>001</id>
<name>Kazuki</name>
</user>
With the JAXB implementation of the JDK, I could easily change the number of indented characters. What about other implementations! ??
Recommended Posts