質問

I'm using java's jaxb to create XML files from java objects. The problem I'm facing is the exact opposite as stated here: LinqToXml does not handle nillable elements as expected

In short: I want to properly depict members that are null in the resulting xml file.

I have following member in my class

  @XmlElement (name = "order-detail", nillable = true)
  private String orderDetail;

if I marshal an instance of this class, the resulting xml element is

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

Since also non-technicians are reading, maybe also manipulating, the file, I'd rather have it that way

<order-detail />

since I don't want to confuse them. So how can I achieve this?

UPDATE

Using an empty string instead of null

  @XmlElement (name = "order-detail", nillable = true)
  private String orderDetail = "";

yields

<order-detail></order-detail>

SSCCE

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Example
{
  public static void main(String[] args) throws JAXBException
  {
    Data data = new Data();
    JAXBContext context = JAXBContext.newInstance(Data.class);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(data, System.out);
  }

  @XmlRootElement(name = "data")
  static class Data
  {
    private String orderDetail;

    @XmlElement (name = "order-detail", nillable = true)
    public String getOrderDetail()                  { return orderDetail;             }
    public void setOrderDetail(String orderDetail)  { this.orderDetail = orderDetail; }
  }
}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data>
    <order-detail xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</data>
役に立ちましたか?

解決

JAXB will marshal an empty string ("") as an empty element. You could change your code so that when the field has a value of ("") the property reports a null value.

  @XmlRootElement(name = "data")
  static class Data
  {
    private String orderDetail = "";

    @XmlElement (name = "order-detail", nillable = true)
    public String getOrderDetail() {
        if(orderDetail.length() == 0) {
            return null;
        }
        return orderDetail;
    }
    public void setOrderDetail(String orderDetail)  { 
        if(null == orderDetail) {
            this.orderDetail = "";
        } else {
            this.orderDetail = orderDetail; 
        }
    }
  }

Normally an XmlAdapter is used to "fix up" values, but the JAXB reference implementation does not apply an XmlAdapter to null values.


Note

In short: I want to properly depict members that are null in the resulting xml file.

Any empty element is not a valid representation of null in XML.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top