JAXB Marshall/unmarshall

115 Views Asked by At

I have got 2 Classes : A and Test, that are defined in diffenent .java-files. Class Test as a field of type A. Now I need to be able to marshall/unmarshall both these classes, so I would need to put an XMLRootElement to both classes. Is it possible? Or do I need some wrapper for it? Coudl not find anything in Google for it.

Greets, Jeff

1

There are 1 best solutions below

1
On

It certainly is possible and you don't need any sort of wrapper. Here's an example:

ItemA.java

package answer;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "ItemA")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class ItemA {

    private ItemB One = new ItemB();
    private ItemB Two = new ItemB();

}

ItemB.java

package answer;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "ItemB")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class ItemB {

    private int One = 1;
    private int Two = 2;
}

Proof this works

package answer;

import javax.xml.bind.JAXB;
import java.io.StringWriter;

public class Test {

    public static void main(String[] args) {
        ItemA itemA = new ItemA();
        ItemB itemB = new ItemB();

        StringWriter sw1 = new StringWriter();
        JAXB.marshal(itemA, sw1);
        System.out.println(sw1.toString());

        StringWriter sw2 = new StringWriter();
        JAXB.marshal(itemB, sw2);
        System.out.println(sw2.toString());

    }

}