使用JAXBContext和Marshaller对象转换为XML和XML

时间:2011-06-16 05:54:18

标签: java xml jaxb

    BufferedWriter out = new BufferedWriter(fstream);
    try {
        JAXBContext context = JAXBContext.newInstance(NarociloType.class);

        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        m.marshal(parameters, out);
        out.newLine();
    } catch (PropertyException pe) {
        // TODO: Add catch code
        pe.printStackTrace();
    } catch (JAXBException jaxbe) {
        // TODO: Add catch code
        jaxbe.printStackTrace();
    }

但是空类型不会存储到XML中。例如:

NarociloType.date = null 

但我在xml <date></date>中看不到。 JAXB编组不会为空值创建空元素

我是否可以使用JAXBContext将XML更改为对象?

2 个答案:

答案 0 :(得分:1)

注意:以下示例适用于EclipseLink JAXB (MOXy),但不适用于Java SE 6中包含的JAXB参考实现。

如果您使用MOXy作为JAXB提供程序(我是技术主管),那么您可以在此用例中使用XmlAdapter

<强> DateAdatper

import java.util.Date;

import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import forum235.DateAdapter.AdaptedDate;

public class DateAdapter extends XmlAdapter<AdaptedDate, Date> {

    @Override
    public Date unmarshal(AdaptedDate adaptedDate) throws Exception {
        return adaptedDate.date;
    }

    @Override
    public AdaptedDate marshal(Date date) throws Exception {
        AdaptedDate adaptedDate = new AdaptedDate();
        adaptedDate.date = date;
        return adaptedDate;
    }

    static class AdaptedDate {
        @XmlValue
        public Date date;
    }

}

<强>根

import java.util.Date;

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

@XmlRootElement
public class Root {

    private Date date;

    @XmlJavaTypeAdapter(DateAdapter.class)
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

}

<强>演示

import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Root root = new Root();
        marshaller.marshal(root, System.out);

        root.setDate(new Date());
        marshaller.marshal(root, System.out);
    }

}

<强>输出

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <date/>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <date>2011-06-16T09:16:09.452</date>
</root>

<强> jaxb.properties

您使用MOXy作为JAXB提供程序,您需要在与域类相同的程序包中提供名为jaxb.properties的文件,并使用以下条目:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

有关XmlAdapter的更多信息

答案 1 :(得分:0)