Marek Klein
Marek Klein

Reputation: 1490

XmlAdapter depending on previously parsed data

I need to read/write an object from/to xml file. The object contains an array of elements.

Let's say that Element class looks as follows:

public class Element() {
    private BigInteger v;
    private BigInteger p;

    public Element(BigInteger v, BigInteger p) {...}
    public getV() {...}
    public getP() {...}
}

And MyObject class looks as follows:

public class MyObject {
    private ArrayList<Element> elements;

    public MyObject () {
        ...
    }

    @XmlElementWrapper(name="Elements", required=true)
    @XmlElement(name="element")
    @XmlJavaTypeAdapter(value = ElementAdapter.class, type = Element.class)
    public ArrayList<Element> getElements() {
        return this.elements;
    }

    public void setElements(ArrayList<Element> elements) {
        this.elements = elements;
    }
}

Element constructor needs 2 input parameters (e.g., Element e = new Element(v, p);). However in MyObject all elements have the same value p and I would like to store it in the file just once. It means that at some point I would read the value p and afterwards I would just read values v and create elements using v and p.

In other words I would change MyObject class to something like this:

public class MyObject {
    private ArrayList<Element> elements;
    private BigInteger commonP;

    public MyObject(ArrayList<Element> elements) {
        this.elements = elements;
        this.commonP = elements.get(0).getP();
    }
    ...
    @XmlElement(name="P")
    public BigInteger getCommonP() {
        return this.commonP;
    }

    public void setCommonP(BigInteger P) {
        this.commonP = P;
    }

Then I need to somehow pass the commonP to ElementAdapter to create Element objects.

public class ElementAdapter extends XmlAdapter<BigInteger, Element>{

    @Override
    public Element unmarshal(BigInteger v) throws Exception {
        // Note that commonP does not exist in this scope
        return new Element(v, commonP);
    }

    @Override
    public BigInteger marshal(element v) throws Exception {
        return v.toBigInteger();
    }
}

My question is whether it is possible to set commonP while parsing xml and pass it to ElementAdapter.

Upvotes: 0

Views: 48

Answers (0)

Related Questions