4

JAXBを使用してJavaオブジェクトをマーシャリングすると、xml要素の下に表示されます

<error line="12" column="" message="test" />

しかし、私は以下のようなxmlが必要です

<error line="12" message="test" />

列の値が空の場合は、上記のようにxmlを取得する必要があります。それ以外の場合は、要素の列属性を取得する必要があります。

それを取得する方法はありますか?

4

1 に答える 1

7

String対応するフィールド/プロパティに空の値が含まれている場合にのみ、属性は空の値でマーシャリングされStringます。値がnullの場合、属性はマーシャリングされません。

package forum13218462;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Root {

    @XmlAttribute
    String attributeNull;

    @XmlAttribute
    String attributeEmpty;

    @XmlAttribute(required=true)
    String attributeNullRequired;

}

デモ

package forum13218462;

import javax.xml.bind.*;

public class Demo {

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

        Root root = new Root();
        root.attributeNull = null;
        root.attributeEmpty = "";
        root.attributeNullRequired = null;

        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 attributeEmpty=""/>
于 2012-11-04T13:58:36.893 に答える