Let’s say I have class Person:
class Person{
String firstName;
String lastName;
String email;
}
XML has format:
<person>
<firstName value="asd" />
<lastName value="bcd" />
<email value="qwe" />
</person>
I can unmarshal/marshal this class using own XmlAdapter implementation for each
of field FirstNameAdapter, LastNameAdapter, EmailAdapter. As you can see each field represented in similar way – field name as xml element and field value as element’s attribute. Is it possible to create “universal” adapter to which I’ll be able to transfer name of the field and it will extract value of that field ?
P.S. I know about MOXy JAXB implementation, but I’m wondering if it is possible by means of reference JAXB implementation.
Thanks!
You can use an
XmlAdapterlike this:The idea here is that XML Schema and therefore also JAXB has a clear distinction between element names and content types, even though many documents have a clear one-to-one correspondence between these two. So in the above code, the type
Valueddescribes something that has avalueattribute, without regards for the element name. The members you want to serialize are annotated as@XmlElementwith no name included in that annotation. So they will generate elements with a name derived from the name of the member. The@XmlJavaTypeAdapterannotation will cause the serializer to treat these members as if their types vereValued. So that is what their XML content type will be.The schema for the above code looks like this: