7

How I can retrieve null value, when unmarshalling, if inside XML attribute value is empty ? Now I make inside my getters checking for null :

public String getLabel() {
    if (label.isEmpty()) {
        return null;
    }
    else {
        return label;
    }
}

But may be exist some other, more elegant way?

Thanks.

4

2 に答える 2

10

XMLは多かれ少なかれ次のように見えると思います。

    <myElement></myElement>

これは、残念ながら、空の文字列を渡していることを意味します。

合格したいnull場合は、2つのオプションがあります。

  1. このタグをまったく渡さないでください(XMLに<myElement/>タグを含めないでください)。
  2. を使用しxsi:nilます。

を使用する場合xsi:nilは、最初に(XSDファイル内の)xml要素を次のように宣言する必要がありますnilable

    <xsd:element name="myElement" nillable="true"/>

次に、nullXML内で値を渡すには、次のようにします。

    <myElement xsi:nil="true"/>

またはこれ:

    <myElement xsi:nil="true"></myElement>

このようにして、JAXBnullは、空の文字列の代わりに渡すことを認識します。

于 2012-06-03T11:15:14.797 に答える
7

npeの答えは良いものであり、どのようにnull表現したいかを指定することも私の推奨事項です。xsi:nilマーシャリングするには、プロパティに次のように注釈を付ける必要があります(JSONおよびXMLへのバインド-Nullの処理を参照)。

@XmlElement(nillable=true)
public String getLabel() {
    return label;
}

XML表現を変更したくない場合は、XmlAdapter:を使用できます。

EmptyStringAdapter

package forum10869748;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class EmptyStringAdapter extends XmlAdapter<String, String> {

    @Override
    public String unmarshal(String v) throws Exception {
        if("".equals(v)) {
            return null;
        }
        return v;
    }

    @Override
    public String marshal(String v) throws Exception {
        return v;
    }

}

フー

注釈XmlAdapterを使用してを参照します。@XmlJavaTypeAdapterこれをすべての文字列に適用したい場合はXmlAdapter、パッケージレベルで登録できます(JAXBおよびパッケージレベルのXmlAdaptersを参照)。

package forum10869748;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Foo {

    private String label;

    @XmlJavaTypeAdapter(EmptyStringAdapter.class)
    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

}

デモ

package forum10869748;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum10869748/input.xml");
        Foo foo = (Foo) unmarshaller.unmarshal(xml);

        System.out.println(foo.getLabel());
    }

}

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<foo>
    <label></label>
</foo>

出力

null
于 2012-06-04T11:38:18.067 に答える