Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1026921
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T12:09:28+00:00 2026-05-16T12:09:28+00:00

I’m working with a XML structure that looks like this: <ROOT> <ELEM_A> <A_DATE>20100825</A_DATE> <A_TIME>141500</A_TIME>

  • 0

I’m working with a XML structure that looks like this:

<ROOT>
    <ELEM_A>
        <A_DATE>20100825</A_DATE>
        <A_TIME>141500</A_TIME>
        <!-- other elements, maybe also other or date/time combinations -->
        <STRING>ABC</STRING>
    <ELEM_A>
    <ELEM_B>
        <B_DATE>20100825</B_DATE>
        <B_TIME>153000</B_TIME>
        <NUM>123</NUM>
        <C_DATE>20100825</C_DATE>
        <C_TIME>154500</C_TIME>
    </ELEM_B>
</ROOT>

And I want to map date and time to a single Date or Calendar property in my bean. Is this possible using jaxb annotations? The class javax.xml.bind.annotation.adapters.XmlAdapter looks like it might be able to do this, but I have to admit I don’t fully understand its javadoc.

A workaround would be to create additional setters for the date and time strings that set the corresponding values in a Calendar property like this:

private Calendar calendar;

public void setDate(String date) {
    if (calendar == null) {
        calendar = new GregorianCalendar();
    }
    calendar.set(YEAR, Integer.parseIn(date.substring(0, 4)));
    calendar.set(MONTH, Integer.parseIn(date.substring(4, 6))-1);
    calendar.set(DAY_OF_MONTH, Integer.parseIn(date.substring(6, 8)));
}

// Similar code for setTime

The problem (apart from the additional code) is that I can’t always guarantee that the date is set before the time value, but I can’t think of a specific example where this might give worng results.

Any examples for an annotation based solution or improvements / counter examples for the code above are appreciated.

Edit: I went with the second answer given by Blaise Doughan, but modified his DateAttributeTransformer to be more flexible and not expect the field name to contain the string “DATE”. The field names are taken from the XmlWriterTransformer annotations on the field:

@Override
public Object buildAttributeValue(Record record, Object instance, Session session) {
    try {
        String dateString = null;
        String timeString = null;

        String dateFieldName = null;
        String timeFieldName = null;
        // TODO: Proper Exception handling
        try {
            XmlWriteTransformers wts = instance.getClass().getDeclaredField(mapping.getAttributeName()).getAnnotation(XmlWriteTransformers.class);
            for (XmlWriteTransformer wt : wts.value()) {
                String fieldName = wt.xpath();
                if (wt.transformerClass() == DateFieldTransformer.class) {
                    dateFieldName = fieldName;
                } else {
                    timeFieldName = fieldName;
                }
            }
        } catch (NoSuchFieldException ex) {
            throw new RuntimeException(ex);
        } catch (SecurityException ex) {
            throw new RuntimeException(ex);
        }

        for(DatabaseField field : mapping.getFields()) {
            XMLField xfield = (XMLField)field;
            if(xfield.getXPath().equals(dateFieldName)) {
                dateString = (String) record.get(field);
            } else {
                timeString = (String) record.get(field);
            }
        }
        return yyyyMMddHHmmss.parseObject(dateString + timeString);
    } catch(ParseException e) {
        throw new RuntimeException(e);
    }
}
  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T12:09:29+00:00Added an answer on May 16, 2026 at 12:09 pm

    Instead of using the JAXB RI (Metro), you could use the MOXy JAXB implementation (I’m the tech lead). It has some extensions that will make mapping this scenario fairly easy.

    jaxb.properties

    To use MOXy as your JAXB implementation you need to add a file named jaxb.properties in the same package as your model classes with the following entry:

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

    Root

    import javax.xml.bind.annotation.*;
    
    @XmlRootElement(name="ROOT")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Root {
    
        @XmlElement(name="ELEM_A")
        private ElemA elemA;
    
        @XmlElement(name="ELEM_B")
        private ElemB elemB;
    
    }
    

    ElemA

    We can leverate @XmlTransformation. It is similar in concept to XmlAdapter, but easier to share among mappings.

    import java.util.Date;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    
    import org.eclipse.persistence.oxm.annotations.XmlReadTransformer;
    import org.eclipse.persistence.oxm.annotations.XmlTransformation;
    import org.eclipse.persistence.oxm.annotations.XmlWriteTransformer;
    import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ElemA {
    
        @XmlTransformation
        @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
        @XmlWriteTransformers({
            @XmlWriteTransformer(xpath="A_DATE/text()", transformerClass=DateFieldTransformer.class),
            @XmlWriteTransformer(xpath="A_TIME/text()", transformerClass=TimeFieldTransformer.class),
        })
        public Date aDate;
    
        @XmlElement(name="STRING")
        private String string;
    }
    

    ElemB

    import java.util.Date;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    
    import org.eclipse.persistence.oxm.annotations.XmlReadTransformer;
    import org.eclipse.persistence.oxm.annotations.XmlTransformation;
    import org.eclipse.persistence.oxm.annotations.XmlWriteTransformer;
    import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ElemB {
    
        @XmlTransformation
        @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
        @XmlWriteTransformers({
            @XmlWriteTransformer(xpath="B_DATE/text()", transformerClass=DateFieldTransformer.class),
            @XmlWriteTransformer(xpath="B_TIME/text()", transformerClass=TimeFieldTransformer.class),
        })
        private Date bDate;
    
        @XmlElement(name="NUM")
        private int num;
    
        @XmlTransformation
        @XmlReadTransformer(transformerClass=DateAttributeTransformer.class)
        @XmlWriteTransformers({
            @XmlWriteTransformer(xpath="C_DATE/text()", transformerClass=DateFieldTransformer.class),
            @XmlWriteTransformer(xpath="C_TIME/text()", transformerClass=TimeFieldTransformer.class),
        })
        private Date cDate;
    
    }
    

    DateAttributeTransformer

    The attribute transformer is responsible for unmarshalling the Date object.

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    
    import org.eclipse.persistence.internal.helper.DatabaseField;
    import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
    import org.eclipse.persistence.mappings.transformers.AttributeTransformer;
    import org.eclipse.persistence.sessions.Record;
    import org.eclipse.persistence.sessions.Session;
    
    public class DateAttributeTransformer implements AttributeTransformer {
    
        private AbstractTransformationMapping mapping;
        private SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
    
        public void initialize(AbstractTransformationMapping mapping) {
            this.mapping = mapping;
        }
    
        public Object buildAttributeValue(Record record, Object instance, Session session) {
            try {
                String dateString = null;
                String timeString = null;
    
                for(DatabaseField field : mapping.getFields()) {
                    if(field.getName().contains("DATE")) {
                        dateString = (String) record.get(field);
                    } else {
                        timeString = (String) record.get(field);
                    }
                }
                return yyyyMMddHHmmss.parseObject(dateString + timeString);
            } catch(ParseException e) {
                throw new RuntimeException(e);
            }
        }
    
    }
    

    DateFieldTransformer

    The field transformers are responsible for marshalling the Date object.

    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
    import org.eclipse.persistence.mappings.transformers.FieldTransformer;
    import org.eclipse.persistence.sessions.Session;
    
    public class DateFieldTransformer implements FieldTransformer {
    
        private AbstractTransformationMapping mapping;
        private SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
    
        public void initialize(AbstractTransformationMapping mapping) {
            this.mapping = mapping;
        }
    
        public Object buildFieldValue(Object instance, String xPath, Session session) {
            Date date = (Date) mapping.getAttributeValueFromObject(instance);
            return yyyyMMdd.format(date);
        }
    
    }
    

    TimeFieldTransformer

    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.eclipse.persistence.mappings.foundation.AbstractTransformationMapping;
    import org.eclipse.persistence.mappings.transformers.FieldTransformer;
    import org.eclipse.persistence.sessions.Session;
    
    public class TimeFieldTransformer implements FieldTransformer {
    
        private AbstractTransformationMapping mapping;
        private SimpleDateFormat HHmmss = new SimpleDateFormat("HHmmss");
    
        public void initialize(AbstractTransformationMapping mapping) {
            this.mapping = mapping;
        }
    
        public Object buildFieldValue(Object instance, String xPath, Session session) {
            Date date = (Date) mapping.getAttributeValueFromObject(instance);
            return HHmmss.format(date);
        }
    
    }
    

    Sample Program

    import java.io.File;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Root.class);
            System.out.println(jc);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            File xml = new File("src/forum41/input.xml");
            Root root = (Root) unmarshaller.unmarshal(xml);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(root, System.out);
        }
    
    }
    

    XML Document

    <ROOT> 
        <ELEM_A> 
            <A_DATE>20100825</A_DATE> 
            <A_TIME>141500</A_TIME>
            <!-- other elements, maybe also other or date/time combinations --> 
            <STRING>ABC</STRING> 
        </ELEM_A> 
        <ELEM_B> 
            <B_DATE>20100825</B_DATE> 
            <B_TIME>153000</B_TIME>
            <NUM>123</NUM> 
            <C_DATE>20100825</C_DATE> 
            <C_TIME>154500</C_TIME>
        </ELEM_B> 
    </ROOT> 
    

    The code as shown above requires EclipseLink 2.2 currently under development. A nightly builds are available here:

    • http://www.eclipse.org/eclipselink/downloads/nightly.php

    The current released version of EclipseLink 2.1 supports the above, but with a slightly different configuration. We can discuss the appropriate setup if you are interested in exploring this option.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I would like to run a str_replace or preg_replace which looks for certain words
I have some data like this: 1 2 3 4 5 9 2 6
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.