Fork me on GitHub

Formatting Data

You may enrich the XPath expressions with formatting patterns. These patterns will be used for reading and writing values so you do not need to care about that yourself.

How do I parse XML values like '20141031' into a java.util.Date object?

Append the keyword ' using ' followed by the format pattern to your XPath expression:

@XBRead("/foo/bar/date using yyyyMMdd")
Date getDate();

How do I write formatted java.util.Date objects?

Just the same like you did with the reading projection:

@XBWrite("/foo/bar/date using yyyyMMdd")
void setDate(Date date);

What about formatting parameters used in a predicate?

If your XPath depends on selecting formatted numbers or dates, you need to use an XPath variable followed by the pattern enclosed in XPath comments.

@XBRead("/foo[@date=$PARAM0(:using MMdd:)]/bar")
String getBar(Date birthdate);

With Java 8 you even can use the Java parameter name directly as XPath variable:

@XBRead("/foo[@date=$BIRHDATE(:using MMdd:)]/bar")
String getBar2(Date birthdate);

Which Format instances are used for which Java type?

Java Type Format used
java.util.Date SimpleDateFormat
java.lang.Number DecimalFormat

How to change the locale used for formatting?

If you need to change the locale used in formatting, you may change the default locale (system wide) or just the locale used by your XBProjector instance:

new XBProjector().config().getTypeConverterAs(DefaultTypeConverter.class).setLocale(Locale.ROOT);

How do I change the timezone?

Your timezone affects parsing of Date objects. To get reproduceable results, the DefaultTypeConverter uses 'GMT' as default. If you have the need to use other timezones, you can specify this:

new XBProjector().config().getTypeConverterAs(DefaultTypeConverter.class).setTimeZone(TimeZone.getDefault());