简体   繁体   中英

Unmarshalling empty xml element jaxb

I have an empty tag like this <tagName/> . When I unmarshalling it if this property is the type of long or float it is null. But if this property is the type of string, the property is tagName = ''; . And after marshalling is <tagName></tagName> . How can I set empty tag name which is string java property to null while unmarshalling?

There are (at least) 2 ways to do this.

  1. If the classes are yourself and not auto-generated from xsd or similar you can use an adapter.

For example a class Cart:

@XmlRootElement(name = "Cart")
@XmlAccessorType(XmlAccessType.FIELD)
public class Cart {

    @XmlJavaTypeAdapter(EmptyTagAdapter.class)
    protected String tagName;
}

can use an adapter like below:

public class EmptyTagAdapter extends XmlAdapter<String, String> {

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

    @Override
    public String unmarshal(String arg0) throws Exception {
       if(arg0.isEmpty()) {
           return null;
       }
        return arg0;
    }
}

For an xml that looks like this:

<Cart>
  <tagName/>
</Cart>

You would get the empty tagName as null.

  1. If your classes are generated from an xsd you could mention that the field can be nillable.

For example as below:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.1">
    <xs:element name="Cart">
        <xs:complexType>
            <xs:all>
                <xs:element name="tagName" type="xs:string" nillable="true" />
            </xs:all>
        </xs:complexType>
    </xs:element>
</xs:schema>

and then you would need to have in your xml with the empty element xsi:nil="true" as this example:

<Cart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <tagName/>
  <tagName xsi:nil="true" />
</Cart>

It would have the same result, the value as null.

The use of the adapter is more to my liking but depends on your case. Hopefully one of the cases covers you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM