読者です 読者をやめる 読者になる 読者になる

JAXB の Marshaller

JAXB の marshal 時に XML 宣言を生成しないようにする

Java SE 6の Javadoc にも記述されていますが、 XML 宣言を出力したくない場合は、プロパティ jaxb.fragment の値を true にします。

jp.pigumer.Data

package jp.pigumer;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Data {

    @XmlElement
    public String elem1;

    @XmlElement
    public String elem2;

}

jp.pigumer.JAXBTest

package jp.pigumer;

import org.junit.Before;
import org.junit.Test;

import javax.xml.bind.*;
import java.io.IOException;
import java.io.StringWriter;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

public class JAXBTest {

    Marshaller marshaller;

    Data sut;

    @Before
    public void setUp() throws JAXBException {
        sut = new Data();
        sut.elem1 = "test1";
        sut.elem2 = "test2";

        JAXBContext context = JAXBContext.newInstance(Data.class);
        marshaller = context.createMarshaller();
    }

    @Test
    public void defaultMarshallerTest() throws JAXBException, IOException {
        String out;
        try (StringWriter wr = new StringWriter()) {
            marshaller.marshal(sut, wr);
            out = wr.toString();
        }
        assertThat(out, is(not(nullValue())));
        System.out.println("default: " + out);
    }

    @Test
    public void fragmentMarshallerTest() throws JAXBException, IOException {
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

        String out;
        try (StringWriter wr = new StringWriter()) {
            marshaller.marshal(sut, wr);
            out = wr.toString();
        }
        assertThat(out, is(not(nullValue())));
        System.out.println("fragment: " + out);
    }
}

実行結果

fragment: <data><elem1>test1</elem1><elem2>test2</elem2></data>
default: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><data><elem1>test1</elem1><elem2>test2</elem2></data>
広告を非表示にする