Selective mapping

24 views
Skip to first unread message

Marre

unread,
Feb 26, 2010, 9:51:20 AM2/26/10
to xmappr
Hi! I have a tiny problem :-)
this is for the sake of the argument my xml:
<root>
<subroot>
<item/>
</subroot>
<subroot2>
<item id="one" val="true"/>
<item id="two" val="true"/>
<item id="three" val="false"/>
</subroot2>
</root>

Currently I'm mapping an entire list of items, but is there a way for
me to only map items whose val is true?

Peter Knego

unread,
Feb 26, 2010, 12:35:23 PM2/26/10
to xma...@googlegroups.com
It's possible with a custom converter.

Normally Xmappr does not make any decisions based on the values of elements or attributes.

Let me know if you need help writing a custom element converter.

Peter

Marko Anic

unread,
Feb 26, 2010, 1:35:50 PM2/26/10
to xma...@googlegroups.com
Ok, thx for the reply.
I'll try on my own, but if I run into any problems, I'll contact you.

--
Marko

Peter Knego

unread,
Feb 26, 2010, 4:07:04 PM2/26/10
to xma...@googlegroups.com
A few things to note:

- You have to implement the ElementConverter interface
- Take a look at the unit tests. There are a few examples that implement ElementConverter.
- When fromElement(..) method is called you are already positioned inside the correct element.

Your fromElement(..) method might look like this

public Object fromElement(XMLSimpleReader reader, MappingContext mappingContext, String defaultValue,
String format, Class targetType, Object targetObject) {

String id = reader.getAttribute(new QName("id"));
String val = reader.getAttribute(new QName("val"));

if
(val.equals("true")) return new Item (id, val);

// result is not used if it's null
return null;
}
I'm assuming here that you have a class Item with Item(String id, String val) consructor.

Good luck..

Peter

Marko Anic

unread,
Mar 4, 2010, 8:08:36 AM3/4/10
to xma...@googlegroups.com
Thanks, Peter! :-)

--
Marko Anić
Reply all
Reply to author
Forward
0 new messages