#0. 准备要转换的xml文件,在Project视界中,右击这个xml文件,在弹出的菜单上选择“Generate XSD schema from XML File...”, 按默认设置生成xsd文件。
将xsd 文件移至#1配置段的configuration/sources/source指定的路径下.
#1. 打开pom.xml, 加入下面的配置段.其中configuration节点中的内容依具体的项目不同而有不同的设定。一般而言,有3处设定:packageName,outputDirectory 和sources,
具体的官方说明文档,请参见:http://www.mojohaus.org/jaxb2-maven-plugin/Documentation/v2.2/xjc-mojo.html
org.apache.maven.plugins
maven-compiler-plugin
1.8
1.8
org.codehaus.mojo
jaxb2-maven-plugin
2.3.1
xjc
xjc
JaxbHelper.Entity
D:\Git\zfq308\JaxbHelper\src\main\java\
D:\Git\zfq308\JaxbHelper\src\main\resources\FeedTestCase1.xsd
View Code
#2. 在POM文件中加入#1所示的xml节点后,在Maven Projects视界窗口,找到你项目的节点,在Plugins节点下,
找到jaxb2节点,展开后,双击执行jaxb2:xjc 任务即可在指定的输出文件夹下生成相应的Entity.
#3. 将xml的数据通过jaxb载入成具体的类对象实例时,可采用下面的代码:本例中,TestSuitesType是xml的根节点。
importJaxbHelper.Entity.TestSuitesType;importjavax.xml.bind.JAXBContext;importjavax.xml.bind.JAXBException;importjavax.xml.bind.Unmarshaller;importjava.io.File;public classApp {public static void main(String[] args) throwsJAXBException {
File file=new File("D:\\Git\\zfq308\\JaxbHelper\\src\\main\\resources\\FeedTestCase1.xml");
JAXBContext jaxbContext= JAXBContext.newInstance(TestSuitesType.class);
Unmarshaller jaxbUnmarshaller=jaxbContext.createUnmarshaller();
TestSuitesType testSuites=(TestSuitesType) jaxbUnmarshaller.unmarshal(file);
Integer i=0; //此行用于断点测试
}
}
请注意:直接执行时,编译器编译通过,但运行时报:Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"TestSuites"). Expected elements are (none)的错误。
究其原因是因为Jaxb并不知道你所生成的这些Java类,谁是主节点。为此,需要在对应xml根节点的类里加入一个标注:@XmlRootElement(name="TestSuites")
加入前为:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name= "TestSuitesType", propOrder = {"testSuite"})public classTestSuitesType {
}
加入后为:
@XmlRootElement(name="TestSuites")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name= "TestSuitesType", propOrder = {"testSuite"})public classTestSuitesType {
}
修改后即可正常使用。
#4. 如XML 有修改需要重新生成xsd、Java类等,可直接删除相应的xsd、java类和META-INF文件夹,必要时再删除target 目录,再重复#2-#3即可。
补充:
在测试的时候发现上述测试代码:
TestSuitesType testSuites = (TestSuitesType) jaxbUnmarshaller.unmarshal(file);
在执行的时候报错:“javax.xml.bind.JAXBElement cannot be cast to 。。。”, 不能直接转换,通过查阅官网资料和https://stackoverflow.com/questions/707084/class-cast-exception-when-trying-to-unmarshall-xml ,改成如下代码:
String xmlPath = App.class.getClassLoader().getResource("Testcases/Book/Config/TestCase_Update.xml").getPath();
File file= newFile(xmlPath);try{
InputStream in= newFileInputStream(file);
Source source= newStreamSource(in);
JAXBContext jaxbContext= JAXBContext.newInstance(TestSuiteType.class);
Unmarshaller jaxbUnmarshaller=jaxbContext.createUnmarshaller();
JAXBElement root = jaxbUnmarshaller.unmarshal(source, TestSuiteType.class);
TestSuiteType testSuite=root.getValue();
Integer i=0; // 此行用于断点测试
}catch(Exception e) { e.printStackTrace(); }
按这种方式执行的代码,似乎不需要为Entity Java Class 加入@XmlRootElement(name="TheNodeName") 节点。操作上也更为便捷。