如何在IJ中使用Jaxb2通过xml定义生成对应的Java Entity类的文件

#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

<build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
                <version>2.3.1</version>
                <executions>
                    <execution>
                        <id>xjc</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!-- The package of your generated sources, Jaxb会按这个Package的层次生成目录,并把Java类生成到这个Package中 -->
                    <packageName>JaxbHelper.Entity</packageName>
                    
                    <!-- The path of your generated sources class, 输出Java类的根目录地址 -->
                    <outputDirectory>D:Gitzfq308JaxbHelpersrcmainjava</outputDirectory>
                    <sources>
                        <!-- 此处为 xsd的路径, Sources节点下可以支持设定多个xsd文件 -->
                        <source>D:Gitzfq308JaxbHelpersrcmain
esourcesFeedTestCase1.xsd</source>
                    </sources>
                </configuration>
            </plugin>
           
        </plugins>
    </build>
View Code

#2. 在POM文件中加入#1所示的xml节点后,在Maven Projects视界窗口,找到你项目的节点,在Plugins节点下,
找到jaxb2节点,展开后,双击执行jaxb2:xjc 任务即可在指定的输出文件夹下生成相应的Entity.


#3. 将xml的数据通过jaxb载入成具体的类对象实例时,可采用下面的代码:本例中,TestSuitesType是xml的根节点。

import JaxbHelper.Entity.TestSuitesType;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;

public class App {
    public static void main(String[] args) throws JAXBException {
        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 class TestSuitesType {

}

加入后为:

@XmlRootElement(name="TestSuites")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TestSuitesType", propOrder = {"testSuite"})
public class TestSuitesType {

}

修改后即可正常使用。


#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 = new File(xmlPath);
        try {

            InputStream in = new FileInputStream(file);
            Source source = new StreamSource(in);
            JAXBContext jaxbContext = JAXBContext.newInstance(TestSuiteType.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            JAXBElement<TestSuiteType> root = jaxbUnmarshaller.unmarshal(source, TestSuiteType.class);
            TestSuiteType testSuite = root.getValue();
          Integer i=0; // 此行用于断点测试
 } catch (Exception e) { e.printStackTrace(); }

 按这种方式执行的代码,似乎不需要为Entity Java Class 加入@XmlRootElement(name="TheNodeName") 节点。操作上也更为便捷。

原文地址:https://www.cnblogs.com/zfq308/p/7093775.html