Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
IS there a way to generate java classes dynamicaly for a structure
like this ?
JAXB implementations provide the ability to generate a Java model from an XML schema. The reference implementation which is included in the JDK starting in Java SE 6 is available at:
<JAVA_HOME>/bin/xjc
An example of generating an object model from an XML schema can be found here:
A small correction, i don't have an xsd for the xml
If you don't have an XML schema you could find a utility to generate an XML schema from an XML document:
Or start from code.
STARTING FROM CODE
You can also start from code and annotate your model to map to the existing XML structure.
Root
package forum11213872;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="Root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="Book")
private List<Book> books;
}
Book
package forum11213872;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Book {
@XmlAttribute
private String name;
@XmlAttribute
private int price;
}
Demo
package forum11213872;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11213872/input.xml");
Root root = (Root) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
input.xml/Output
<Root>
<Book name="harel" price="5" />
<Book name="xml" price="9" />
</Root>