import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlType(propOrder = {"x", "y"})
public class Coordinate
{
private int x;
private int y;
public Coordinate()
{
}
public Coordinate(int x, int y)
{
this.x = x;
this.y = y;
}
@XmlAttribute
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
@XmlAttribute
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
@Override
public String toString()
{
return "X: " + getX() + ", Y: " + getY();
}
}
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlType(propOrder = {"name", "coordinate"})
@XmlRootElement
public class GameObject
{
private String name;
private Coordinate coordinate;
public GameObject()
{
}
public GameObject(String name, Coordinate coordinate)
{
this.name = name;
this.coordinate = coordinate;
}
@XmlAttribute
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@XmlElement
public Coordinate getCoordinate()
{
return coordinate;
}
public void setCoordinate(Coordinate coordinate)
{
this.coordinate = coordinate;
}
@Override
public String toString()
{
return "Name: " + getName() + ", Coordinate: " + getCoordinate();
}
}
public class JAXBTest
{
private final static String PATH = "gameobject.xml";
public static void main(String[] args)
{
GameObject firstObject = new GameObject("firstobject", new Coordinate(10, 10));
try {
JAXBContext context = JAXBContext.newInstance(GameObject.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(firstObject, new File(PATH));
} catch (JAXBException ex) {
Logger.getLogger(JAXBTest.class.getName()).log(Level.SEVERE, null, ex);
}
GameObject anotherObject = null;
try {
JAXBContext context = JAXBContext.newInstance(GameObject.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
anotherObject = (GameObject) unmarshaller.unmarshal(new File(PATH));
} catch (JAXBException ex) {
Logger.getLogger(JAXBTest.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(anotherObject);
}
}
/** Output */
Name: firstobject, Coordinate: X: 10, Y: 10 //Die Werte von GameObject firstObject
/** PATH */
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<gameObject name="firstobject">
<coordinate y="10" x="10"/>
</gameObject>