jaxb使用

转换Xml与java object,一般使用JDom或SAX。但这样手动mapping,代码实在冗长乏味。目前已有jaxb,castor, xstream等类库提供自动映射,如Xfire的webservice就是基于这些类库进行xml解组.

1.已定义xml模板文件
Xml代码
1.<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
2.<job-config> 
3.    <purge-interval>3</purge-interval> 
4.    <db-info> 
5.        <dbtype>Oracle</dbtype> 
6.        <url>oracle:thin:localhost:orcl</url> 
7.        <username>admin</username> 
8.        <password>admin</password> 
9.    </db-info> 
10.    <job-info> 
11.        <frequency> 
12.            <interval-type>WEEKLY</interval-type> 
13.            <interval>10</interval> 
14.            <start-time>09:00</start-time> 
15.        </frequency> 
16.        <objects-component> 
17.            <object> 
18.                <object-name>RUNTIME</object-name> 
19.                <retention>10</retention> 
20.            </object> 
21.            <object> 
22.                <object-name>BUILDTIME</object-name> 
23.                <retention>20</retention> 
24.            </object> 
25.        </objects-component> 
26.        <objects-specific> 
27.            <object> 
28.                <object-name>GOOD</object-name> 
29.                <retention>10</retention> 
30.            </object> 
31.            <object> 
32.                <object-name>BUILDTIME</object-name> 
33.                <retention>20</retention> 
34.            </object> 
35.        </objects-specific> 
36.    </job-info> 
37.</job-config> 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<job-config>
    <purge-interval>3</purge-interval>
    <db-info>
        <dbtype>Oracle</dbtype>
        <url>oracle:thin:localhost:orcl</url>
        <username>admin</username>
        <password>admin</password>
    </db-info>
    <job-info>
        <frequency>
            <interval-type>WEEKLY</interval-type>
            <interval>10</interval>
            <start-time>09:00</start-time>
        </frequency>
        <objects-component>
            <object>
                <object-name>RUNTIME</object-name>
                <retention>10</retention>
            </object>
            <object>
                <object-name>BUILDTIME</object-name>
                <retention>20</retention>
            </object>
        </objects-component>
        <objects-specific>
            <object>
                <object-name>GOOD</object-name>
                <retention>10</retention>
            </object>
            <object>
                <object-name>BUILDTIME</object-name>
                <retention>20</retention>
            </object>
        </objects-specific>
    </job-info>
</job-config>
2.产生xsd文件
手动编写xsd当然很不方便,需要你学习太多xsd的语法细节,在我看来使用时可以参考即可。有一些工具可以自动产生xsd文件。譬如MS Visustido提供了xsd.exe,也有其他开源类库(trang)。
这份代码是使用xsd基于xml来产生xsd,


Shell代码
1."C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe"  E:\temp\JobsConfig.xml /outputdir:/outputdir:e:/temp 
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe"  E:\temp\JobsConfig.xml /outputdir:/outputdir:e:/temp

Xml代码
1.<?xml version="1.0" encoding="utf-8"?> 
2.<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> 
3. . . .  
4.  <xs:element name="job-config"> 
5.    <xs:complexType> 
6.      <xs:sequence> 
7.        <xs:element name="purge-interval" type="xs:string" minOccurs="0" /> 
8.        <xs:element name="db-info" minOccurs="0" maxOccurs="1"> 
9.          <xs:complexType> 
10.            <xs:sequence> 
11.              <xs:element name="dbtype" type="xs:string" minOccurs="0" /> 
12.              <xs:element name="url" type="xs:string" minOccurs="0" /> 
13.              <xs:element name="username" type="xs:string" minOccurs="0" /> 
14.              <xs:element name="password" type="xs:string" minOccurs="0" /> 
15.            </xs:sequence> 
16.          </xs:complexType> 
17.        </xs:element> 
18.<!-- maxOccurs根据需要从unbounded调整为1,则产生的对象从默认的list转为object --> 
19.        <xs:element name="job-info" minOccurs="0" maxOccurs="1"> 
20.          <xs:complexType> 
21.            <xs:sequence> 
22.              <xs:element name="frequency" minOccurs="0" maxOccurs="1"> 
23.                <xs:complexType> 
24.                  <xs:sequence> 
25.                    <xs:element name="interval-type" type="xs:string" minOccurs="0" /> 
26.                    <xs:element name="interval" type="xs:string" minOccurs="0" /> 
27.                    <xs:element name="start-time" type="xs:string" minOccurs="0" /> 
28.                  </xs:sequence> 
29.                </xs:complexType> 
30.              </xs:element> 
31.              <xs:element name="objects-component" minOccurs="0" maxOccurs="1"> 
32.                <xs:complexType> 
33.                  <xs:sequence> 
34.                    <xs:element ref="object" minOccurs="0" maxOccurs="unbounded" /> 
35.                  </xs:sequence> 
36.                </xs:complexType> 
37.              </xs:element> 
38.              <xs:element name="objects-specific" minOccurs="0" maxOccurs="1"> 
39.                <xs:complexType> 
40.                  <xs:sequence> 
41.                    <xs:element ref="object" minOccurs="0" maxOccurs="unbounded" /> 
42.                  </xs:sequence> 
43.                </xs:complexType> 
44.              </xs:element> 
45.            </xs:sequence> 
46.          </xs:complexType> 
47.        </xs:element> 
48.      </xs:sequence> 
49.    </xs:complexType> 
50.  </xs:element> 
51.   . . .  
52.  </xs:element> 
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
. . .
  <xs:element name="job-config">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="purge-interval" type="xs:string" minOccurs="0" />
        <xs:element name="db-info" minOccurs="0" maxOccurs="1">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="dbtype" type="xs:string" minOccurs="0" />
              <xs:element name="url" type="xs:string" minOccurs="0" />
              <xs:element name="username" type="xs:string" minOccurs="0" />
              <xs:element name="password" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
<!-- maxOccurs根据需要从unbounded调整为1,则产生的对象从默认的list转为object -->
        <xs:element name="job-info" minOccurs="0" maxOccurs="1">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="frequency" minOccurs="0" maxOccurs="1">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="interval-type" type="xs:string" minOccurs="0" />
                    <xs:element name="interval" type="xs:string" minOccurs="0" />
                    <xs:element name="start-time" type="xs:string" minOccurs="0" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
              <xs:element name="objects-component" minOccurs="0" maxOccurs="1">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element ref="object" minOccurs="0" maxOccurs="unbounded" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
              <xs:element name="objects-specific" minOccurs="0" maxOccurs="1">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element ref="object" minOccurs="0" maxOccurs="unbounded" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
   . . .
  </xs:element>
3.运行xjc命令由xsd生成java对象

可将JAXB的xjc.bat配置为Eclipse的external tool.对象如下,


4.依据xsd格式从xml中读取数据,unmarshal

Java代码
1.File xmlDocument = new File("res/JobsConfig.xml");  
2.JAXBContext jaxbContext = JAXBContext.newInstance("generated");  
3.            Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();  
4.            SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");  
5.            Schema schema = schemaFactory.newSchema(new File("res/JobsConfig.xsd"));  
6.            unMarshaller.setSchema(schema);  
7. 
8.            JobConfig config = (JobConfig) unMarshaller.unmarshal(xmlDocument);  
9. 
10.            System.out.println("purge-interval: " + config.getPurgeInterval());  
11. 
12.            DbInfo dbInfo = config.getDbInfo();  
13. 
14.            System.out.println("DB type:" + dbInfo.getDbtype());  
15.            System.out.println("Url type:" + dbInfo.getUrl().trim());  
16.            System.out.println("Username type:" + dbInfo.getUsername());  
17.            System.out.println("Password type:" + dbInfo.getPassword());  
18. 
19.            JobInfo jobInfo = config.getJobInfo();  
20.            System.out.println("Frequency:" + jobInfo.getFrequency().getStartTime());  
21. 
22.        }  
23.        catch (JAXBException e)  
24.        {  
25.            System.out.println(e.toString());  
26.        }  
27.        catch (SAXException e)  
28.        {  
29.            System.out.println(e.toString());  
30.        } 
File xmlDocument = new File("res/JobsConfig.xml");
JAXBContext jaxbContext = JAXBContext.newInstance("generated");
Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = schemaFactory.newSchema(new File("res/JobsConfig.xsd"));
unMarshaller.setSchema(schema);

JobConfig config = (JobConfig) unMarshaller.unmarshal(xmlDocument);

System.out.println("purge-interval: " + config.getPurgeInterval());

DbInfo dbInfo = config.getDbInfo();

System.out.println("DB type:" + dbInfo.getDbtype());
System.out.println("Url type:" + dbInfo.getUrl().trim());
System.out.println("Username type:" + dbInfo.getUsername());
System.out.println("Password type:" + dbInfo.getPassword());

JobInfo jobInfo = config.getJobInfo();
System.out.println("Frequency:" + jobInfo.getFrequency().getStartTime());

}
catch (JAXBException e)
{
System.out.println(e.toString());
}
catch (SAXException e)
{
System.out.println(e.toString());
}


5.构造java对象,产生xml数据,marshal


Java代码
1.                      File xmlDocument = new File("jobConfig.xml");  
2.    JAXBContext jaxbContext = JAXBContext.newInstance("generated");  
3.    Marshaller marshaller = jaxbContext.createMarshaller();  
4.    marshaller.setProperty(  
5.        Marshaller.JAXB_FORMATTED_OUTPUT,  
6.        true);  
7.    ObjectFactory factory = new ObjectFactory();  
8. 
9.    JobConfig config = factory.createJobConfig();  
10.    config.setPurgeInterval("3");  
11.    // construct db info  
12.    DbInfo dbInfo = factory.createJobConfigDbInfo();  
13.    dbInfo.setDbtype("Oracle");  
14.    dbInfo.setUrl("oracle:thin:localhost:orcl");  
15.    dbInfo.setUsername("admin");  
16.    dbInfo.setPassword("admin");  
17.    config.setDbInfo(dbInfo);  
18. 
19.    // construct job info  
20.    JobInfo jobInfo = factory.createJobConfigJobInfo();  
21.    // job info - frequency  
22.    Frequency frequency = factory.createJobConfigJobInfoFrequency();  
23.    frequency.setInterval("10");  
24.    frequency.setIntervalType("WEEKLY");  
25.    frequency.setStartTime("09:00");  
26.    jobInfo.setFrequency(frequency);  
27.    // job info - ObjectsComponent  
28.    ObjectsComponent objectComponet = factory.createJobConfigJobInfoObjectsComponent();  
29.    Object runtimeObj = factory.createObject();  
30.    runtimeObj.setObjectName("RUNTIME");  
31.    runtimeObj.setRetention("10");  
32.    objectComponet.getObject().add(  
33.        runtimeObj);  
34.    Object buildtimeObj = factory.createObject();  
35.    buildtimeObj.setObjectName("BUILDTIME");  
36.    buildtimeObj.setRetention("20");  
37.    objectComponet.getObject().add(  
38.        buildtimeObj);  
39.    jobInfo.setObjectsComponent(objectComponet);  
40.    // job info - ObjectsSpecific  
41.    ObjectsSpecific objectSpecfic = factory.createJobConfigJobInfoObjectsSpecific();  
42.    Object tObj1 = factory.createObject();  
43.    tObj1.setObjectName("GOOD");  
44.    tObj1.setRetention("10");  
45.    objectSpecfic.getObject().add(  
46.        tObj1);  
47.    Object tObj2 = factory.createObject();  
48.    tObj2.setObjectName("FAT");  
49.    tObj2.setRetention("20");  
50.    objectSpecfic.getObject().add(  
51.        buildtimeObj);  
52.    jobInfo.setObjectsSpecific(objectSpecfic);  
53. 
54.    config.setJobInfo(jobInfo);  
55. 
56.    // marshal to file  
57.    marshaller.marshal(  
58.        config,  
59.        new FileOutputStream(xmlDocument));  
60.    // marshal to console  
61.    marshaller.marshal(  
62.        config,  
63.        System.out);  
64.}  
65.catch (IOException e)  
66.{  
67.    System.out.println(e.toString());  
68.}  
69.catch (JAXBException e)  
70.{  
71.    System.out.println(e.toString());  
72.} 

你可能感兴趣的:(eclipse,oracle,xml,webservice,Microsoft)