Help us understand the problem. What is going on with this article?

JDKのJAXB実装でインデントを半角スペース2文字にする方法

JDKのJAXB実装(JDK 10までJDKに内臓されている実装 = com.sun.xml.bind:jaxb-impl)を使ってインデント付きのXMLを出力しようとすると、デフォルトだとインデントは半角スペース4文字になります。

モデル
@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;
  }
}
JAXBを使ったXML出力処理
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());
出力されるXML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
    <id>001</id>
    <name>Kazuki</name>
</user>

JDKのJAXB実装を使ってインデント文字列を指定する

JDKのJAXB実装を利用する場合は、com.sun.xml.internal.bind.indentStringプロパティにインデント文字列を指定することができます。

インデント文字列の指定例
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文字
StringWriter writer = new StringWriter();
marshaller.marshal(user, writer);
System.out.println(writer.toString());
出力されるXML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
  <id>001</id>
  <name>Kazuki</name>
</user>

まとめ

JDKのJAXB実装だと簡単にインデント文字数を変更することができました。他の実装はどうなのかな!?

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away