1

I'm trying to optimize my code during the unmarhal of an XML source. I have this xml:

<Parent name="X">
    <List>
        <Element name="A">
        <Element name="B">
        <Element name="C">
    </List>
</Parent>
<Parent name="Y">
    <List>
        <Element name="A">
        <Element name="B">
        <Element name="C">
    </List>
</Parent>

I want to use the Parent's name value into the Element because if the parent 's name is X the elements name will be X+element.getName(), otherwise it will be Y+element.getName(). What I'm trying to do is to set the correct value during the unmarshal process, in the setName(String name) method of the Element bean. This becaus I don't want to cycle over Parents and Elements after the unmarshalling. The problem is that the JAX-B unmarshal approach is bottom up: it creates the object Element before creating object Parent so I don't know how to get the parent attribute name. Is there a way to change this behaviour?

DeooK
  • 535
  • 3
  • 8
  • 23

1 Answers1

1

You can create a method void afterUnmarshal(Unmarshaller, Object parent) that will be called after unmarshalling. In this method you could change the name property of your object as required.

You might also want to annotate your elements property with @XmlElementWrapper(name="List") to make Element objects direct children of Parent object.

ps. This answer is almost 1:1 with the answer in the following question:

JAXB / XJC parent-child-parent navigation

lexicore
  • 42,748
  • 17
  • 132
  • 221
  • Thanks, it seems what I need to. I have a doubt about XmlElementWrapper: I'm not sure to have understood where I need to put the annotation – DeooK Jan 05 '18 at 13:57