注意:我是
EclipseLink JAXB (MOXy)领导者,也是
JAXB (JSR-222)专家组的成员.
IS there a way to generate java classes dynamicaly for a structure
like this ?
JAXB实现提供了从XML模式生成Java模型的能力.从Java SE 6开始的JDK中包含的参考实现可在以下位置获得:
/bin/xjc
可以在此处找到从XML模式生成对象模型的示例:
A small correction,i don’t have an xsd for the xml
如果您没有XML模式,您可以找到一个实用程序来从XML文档生成XML模式:
或者从代码开始.
从代码开始
您还可以从代码开始并注释模型以映射到现有的XML结构.
根
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 books;
}
书
package forum11213872;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Book {
@XmlAttribute
private String name;
@XmlAttribute
private int price;
}
演示
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中/输出