有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JAXB Marshaller不需要值为null或空的元素

当我使用JAXB时,我不想要空的XML应答器

POJO代码:

@XmlRootElement(name = "LIGNE")
public class Ligne {

    private String rideCount;

    @XmlElement(name = "NB_TRAJET")
    public String getRideCount() {
        return rideCount;
    }

    public void setRideCount(String rideCount) {
        this.rideCount = rideCount;
    }
}

JAXB代码:

public String jaxbMoReportsObjectToXML(MoReports moReports) {
    String xmlString = "";
    try {
        JAXBContext context = JAXBContext.newInstance(MoReports.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        StringWriter sw = new StringWriter();
        m.marshal(moReports, sw);
        xmlString = sw.toString();
     } catch (JAXBException e) {
        throw new TechnicalException(e.getMessage());
     }
     return xmlString;
}

包裹信息代码:

@XmlJavaTypeAdapters({ @XmlJavaTypeAdapter(value = StringAdapter.class, type = String.class) })
package com.rivasi.business.aipenet.bean;

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

StringAdapter代码:

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

public class StringAdapter extends XmlAdapter<String, String> {

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

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

}

我找到了一个解决方案:

<LIGNES>
    <LIGNE>
        <NB_TRAJET/>
    </LIGNE>
    <LIGNE>
        <NB_TRAJET>ZONE3</NB_TRAJET>
    </LIGNE>
    <LIGNE>
        <NB_TRAJET/>
    </LIGNE>
    <LIGNE>
        <NB_TRAJET/>
    </LIGNE>
    <LIGNE>
        <NB_TRAJET/>
    </LIGNE>
</LIGNES>

<LIGNES>
    <LIGNE>
        <NB_TRAJET></NB_TRAJET>
    </LIGNE>
    <LIGNE>
        <NB_TRAJET>ZONE3</NB_TRAJET>
    </LIGNE>
    <LIGNE>
        <NB_TRAJET></NB_TRAJET>
    </LIGNE>
    <LIGNE>
        <NB_TRAJET></NB_TRAJET>
    </LIGNE>
    <LIGNE>
        <NB_TRAJET></NB_TRAJET>
    </LIGNE>
</LIGNES>

但我想:

<LIGNES>
    <LIGNE>
        <NB_TRAJET>ZONE3</NB_TRAJET>
    </LIGNE>
</LIGNES>

共 (0) 个答案