Search code examples
javaxmlxstream

Xstream.toXML() XMLGregorianCalendar should not have child elements


Below is the sample code.

public class Test {

    public static void main(String[] args) throws DatatypeConfigurationException {
        GregorianCalendar cal = new GregorianCalendar();
        XMLGregorianCalendar xmlBirthDt = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), 
                                    cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
        XStream x = new XStream();
        x.alias("date", XMLGregorianCalendar.class);
        x.addDefaultImplementation(com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.class, javax.xml.datatype.XMLGregorianCalendar.class);
        String g = x.toXML(xmlBirthDt);

        System.out.println(g);

    }
}

And below is the output

<date>
    <year>2018</year>
    <month>10</month>
    <day>15</day>
    <timezone>-2147483648</timezone>
    <hour>-2147483648</hour>
    <minute>-2147483648</minute>
    <second>-2147483648</second>
</date>

Below is what I'm expecting (when the generated XML is validated against the schema, it is throwing errors: element date has child elements which is not accepted)

<date>10-15-2018</date>

I can't change the libraries used or change the schema as this is a modification to the existing huge code base. Please help me.


Solution

  • I solved it by implementing Converter and registering with Xstream. Below is the final code.

    public static void main(String[] args) throws DatatypeConfigurationException {
        GregorianCalendar cal = new GregorianCalendar();
        XMLGregorianCalendar xmlBirthDt = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), 
                                    cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
    
        XStream x = new XStream();
        x.alias("date", com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.class);
        x.registerConverter(new Converter() {
            @Override
            public boolean canConvert(Class arg0) {
                return arg0.equals(com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.class);
            }
    
            @Override
            public Object unmarshal(HierarchicalStreamReader arg0, UnmarshallingContext arg1) {
                return null;
            }
    
            @Override
            public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
                XMLGregorianCalendar x = (XMLGregorianCalendar) arg0;
                arg1.setValue(x.toString());
            }
        });
    
        String g = x.toXML(xmlBirthDt);
    
        System.out.println(g);
    }