惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
Martin Fowler
Martin Fowler
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
V
Visual Studio Blog
博客园_首页
Engineering at Meta
Engineering at Meta
The Cloudflare Blog
MongoDB | Blog
MongoDB | Blog
Blog — PlanetScale
Blog — PlanetScale
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
D
Docker
博客园 - 司徒正美
S
SegmentFault 最新的问题
M
MIT News - Artificial intelligence
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
U
Unit 42
J
Java Code Geeks
A
About on SuperTechFans
N
Netflix TechBlog - Medium
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
Security Affairs
I
Intezer
Cisco Talos Blog
Cisco Talos Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
B
Blog RSS Feed
P
Privacy & Cybersecurity Law Blog
T
Tenable Blog
T
Threatpost
H
Hacker News: Front Page
G
Google Developers Blog
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research
L
Lohrmann on Cybersecurity
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
A
Arctic Wolf
S
Secure Thoughts
GbyAI
GbyAI
NISL@THU
NISL@THU
S
Security @ Cisco Blogs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Webroot Blog
Webroot Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
O
OpenAI News
Spread Privacy
Spread Privacy
Application and Cybersecurity Blog
Application and Cybersecurity Blog

博客园 - 听雨

在windows下使用COSCMD时因Python版本不支持导致报SafeConfigParser不支持的错误 Jmeter & TICK 关于KOBE 退役 2011/10/14 leave foxconn company,and join the MorningStar at 2011.10.18 http://www.rayfile.com/files/933f60a6-d0d5-11dd-a8f8-0014221b798a/ SMTP 注冊CDO.Message Bear Charactors http://pxzx.hitsz.edu.cn/pxzx/announce/show.php?announceid=156 PDF-XChange Version 3.6.0 SN wmi 屬性查詢 SQL中取得漢字拼音首字母或五筆首鍵編碼 工作日計算 Three Tier Code generation with Codesmith 修改鄒建 老師的SQL PivotTable,增加同分組非交叉欄位 JS Tool(Format) [转贴]Js中 关于top、clientTop、scrollTop、offsetTop等 类似gmail添加附件 JS -Table排序类 JavaScript 日期联动选择器
如何在IJ中使用Jaxb2通过xml定义生成对应的Java Entity类的文件
听雨 · 2017-06-29 · via 博客园 - 听雨

#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:\Git\zfq308\JaxbHelper\src\main\java\</outputDirectory>
                    <sources>
                        <!-- 此处为 xsd的路径, Sources节点下可以支持设定多个xsd文件 -->
                        <source>D:\Git\zfq308\JaxbHelper\src\main\resources\FeedTestCase1.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") 节点。操作上也更为便捷。