2013年9月16日星期一

JDev_042:怎样从XML得到Java?

开发运行环境:JDeveloper 11.1.1.7

本文探讨的问题是:如果你已经有一个XML文件,如何它转换为Java?
这里需要用到JAXB的技术,关于JAXB的介绍,请参考《JAXB介绍》,本文不再赘述。
从XML到Java的过程,用专业的术语表示就是Unmarshal。

1. 原始XML文件:rss.xml
这里以某博客的RSS订阅的XML为例,文件内容比较大,从略。

2. 根据XML文件生成XML Schema文件



3. 根据XML Schema生成JAXB对象
可以发现自动生成的Rss.java中,还有一个内部类:Channel,Channel还有两个内部类:Item和Link。


4. 修改Rss.java
增加main方法如下:
    public static void main(String[] args) throws JAXBException, SAXException {
        JAXBContext jaxbctx = JAXBContext.newInstance("xml2java.generated");
        Unmarshaller unm = jaxbctx.createUnmarshaller();
        File xml =
            new File("D:/JDevRuntime/JDev11117/mywork/Xml2Java/Xml2Java/rss.xml");
        Rss rss = (Rss)unm.unmarshal(xml);
        System.out.println(rss.getChannel().getDescription());
        for (Rss.Channel.Item i : rss.getChannel().getItem()) {
            System.out.println(i.getTitle() + " - " + i.getPubDate());
        }
    }
main函数中使用了UnMarshaller对象,分析XML文件内容,返回Rss对象。

5. 运行Rss.java
输出如下,可以看到,XML内容被Unmarshal成了Java对象。

Weblog for the AMIS Technology corner
How to run into and resolve EL PropertyNotFound exception and
          propertyNotReadable in JSF with private inner class - Thu, 23 Jun 2011 13:22:57 +0000
Using the ADF DVT Radar Graph for comparing series – further analyzing
          ODTUG Kaleidoscope 2011 Session Schedule - Wed, 22 Jun 2011 12:38:51 +0000
JDeveloper 11gR2: New option Test WebService in WSDL editor – quickest
          route to implement and test JAX-WS SOAP WebService - Fri, 17 Jun 2011 14:11:28 +0000
Tracking the moving history of averages and other aggregates –
          Flashback Aggregates in Oracle SQL - Thu, 16 Jun 2011 13:39:07 +0000
Leveraging HTML 5 Navigator API to show the browser’s current location
          on an ADF Faces 11gR2 Thematic Map component - Wed, 15 Jun 2011 09:17:45 +0000
Creating JSON document straight from SQL query – using LISTAGG and
          With Clause - Tue, 14 Jun 2011 10:00:28 +0000
Producing simple Pie Chart straight out of the Oracle Database –
          leveraging dbms_epg, CANVAS, LISTAGG and some JavaScript - Mon, 13 Jun 2011 15:10:33 +0000
Enriching EL evaluation in JSF applications – retrieve values from
          property files or system properties - Sun, 12 Jun 2011 13:42:40 +0000
Leveraging Spring Beans in ADF Faces applications and using the Spring
          PropertyPlaceholderConfigurer bean to dynamically configure bean
          properties from external files - Sat, 11 Jun 2011 08:28:04 +0000
Browser-based log-monitor for database applications (alternative to
          dbms_output,leveraging pipe and Embedded PL/SQL Gateway with a touch
          of AJAX) - Fri, 10 Jun 2011 20:40:54 +0000

Project 下载:Xml2Java.7z

参考文献:
1. http://technology.amis.nl/2011/06/25/turning-any-xml-document-into-java-object-graph-using-jaxb-2-0/

没有评论: