11

で注釈が付けられたJavaプロパティがあり@XmlElement(required=false, nillable=true)ます。オブジェクトがxmlにマーシャリングされると、常にxsi:nil="true"属性とともに出力されます。

要素を書き込むのではなく、要素を書き込まないようにマーシャラーに指示するjaxbcontext / marshallerオプションはありxsi:nilますか?

私はこれに対する答えを探しました、そしてまたコード、afaicsを見ました、それは常にxsi:nilなら書くでしょうnillable = true。私は何かが足りないのですか?

4

1 に答える 1

6

プロパティに注釈が付けられ@XmlElement(required=false, nillable=true)、値がnullの場合、。で書き出されxsi:nil="true"ます。

注釈を付けるだけで@XmlElement、探している動作が得られます。

インポートjavax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; インポートjavax.xml.bind.annotation.XmlElement; インポートjavax.xml.bind.annotation.XmlRootElement;

次のクラスがあるとします。

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement(nillable=true, required=true)
    private String elementNillableRequired;

    @XmlElement(nillable=true)
    private String elementNillbable;

    @XmlElement(required=true)
    private String elementRequired;

    @XmlElement
    private String element;

}

そしてこのデモコード:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Root root = new Root();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        marshaller.marshal(root, System.out);
    }

}

結果は次のようになります。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <elementNillableRequired xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
    <elementNillbable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</root>
于 2011-05-05T13:05:25.657 に答える