I am trying to marshal some classes I designed, with standard JAXB, the classes all have void constructors, this is my first attempt at using JAXB or marshalling/unmarhslling in any language for that matter but as I understand it JAXB should be able to marshall them without a XSD.
The classes are as follow:
@XmlRootElement(name="place")
class Place {
@XmlAttribute
//various fields and get set methods
public Place() {
}
}
@XmlRootElement(name="Arc")
class Arc {
// various fields and get set methods
@XmlAttribute
Place p;
public setPlace(Place p) {
// ...
}
public Arc() {
}
}
@XmlRootElement(name="Transition")
class Transition {
Arc[] a;
public Transition() {
}
}
I can marshall the Place
class but not the Arc
class, the Transition
I didn't even try, the classes have the @XMLPropriety
tags but when it reaches the nested Place
class JAXB doesn't seem to understand which XML object to map it too.
If there is another tag I should be using for the nested class or there's another error I'm overlooking?
The JAXB Marshaller interface is responsible for governing the process of serializing Java content trees i.e. Java objects to XML data. This marshalling to XML can be done to variety of output targets.
Marshalling is the process of writing Java objects to XML file. Unmarshalling is the process of converting XML content to Java objects.
The JAXB annotations defined in the javax. xml. bind. annotations package can be used to customize Java program elements to XML schema mapping.
There is nothing special you need to do to handle nested classes with any JAXB (JSR-222) implementation. Below is a complete example where only one @XmlRootElement
annotation is used:
Transition
package forum13159089;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
class Transition {
Arc[] a;
public Arc[] getA() {
return a;
}
public void setA(Arc[] a) {
this.a = a;
}
}
Arc
package forum13159089;
class Arc {
Place p;
public Place getPlace() {
return p;
}
public void setPlace(Place p) {
this.p = p;
}
}
Place
package forum13159089;
class Place {
}
Demo
package forum13159089;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Transition.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum13159089/input.xml");
Transition transition = (Transition) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(transition, System.out);
}
}
input.xml/Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<transition>
<a>
<place/>
</a>
<a>
<place/>
</a>
</transition>
For More Information
Note: @XMLProperty
is not a JAXB annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With