[Simple-support] Interpret a sub-element as String
Brought to you by:
niallg
|
From: Kiran R. <tec...@gm...> - 2015-02-11 09:18:57
|
Hi,
Here's an XML I have:
<root-element>
<description>lorem-ipsum</description>
<sub-element id="1"><name>Hello World</name></sub-element>
</root-element>
Now, for whatever reason, I want to read the <sub-element> part as a String
rather than as an object - i.e.,
@Root(name="root-element", strict=false)
class RootElement {
@Element(name="description")
String description
//No @Element annotation here.
String subElement;
}
RootElement root = new Persister().read(RootElement.class, INPUT);
RootElement EXPECTED = new RootElement("lorem-ipsum", "<sub-element
id=\"1\"><name>Hello World</name></sub-element>");
assertEquals(EXPECTED, root);
Similarly, when I serialize this RootElement object, I want the string to
appear as a sub-element.
Any idea on how to go about doing this? It looks like I am looking for some
sort of interceptor - I get the partially parsed object and then I can fill
in the missing fields.
I tried using a Converter and the @Convert annotation; I tried implementing
a Visitor - in both cases I got stuck trying to figure out what portion has
been parsed already.
I have temporarily written code to first parse the object with all fields
except subElement; and then set this field using sub-string operations.
However, this is not really scalable - especially when I use sub-element
inside a list, inside other parent elements, or when root-element itself
has other parent elements etc.
|