users@jaxb.java.net

Re: How to get link to Parent Element?

From: Aleksei Valikov <valikov_at_gmx.net>
Date: Thu, 3 Jul 2008 14:04:41 +0200

Hi.

> I am a beginner with JAXB and not using schemas at all, only using manually annotated classes.
>
> There is the following XML:
>
> <A>
> <B />
> <C />
> </A>
>
> So I wrote classes A, B and C and added @XmlRootElement to both.
>
> But now I want to be able inside of classes B and C to ask for the surrounding A.
>
> Is there some "JAXB Magic" that will provide a "Parent Pointer" automatically?
> Or what is the best idea to get that pointer (without changing the above XML schema)?
>
> Maybe the question is silly, but see, I am a total JAXB beginner. ;-)

You can add the afterUnmarshal method to your B and C classes

public void afterUnmarshal(Unmarshaller u, Object parent) {
    this.a = (A) parent;
  }

This callback method will be called by JAXB automatically after unmarshalling.

See here:
https://jaxb.dev.java.net/guide/Mapping_cyclic_references_to_XML.html

Bye.
/lexi