`
bluepopopo
  • 浏览: 91681 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

JAXB使用

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

1.已定义xml模板文件
<?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,

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

<?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
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

                        File xmlDocument = new File("jobConfig.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance("generated");
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(
				Marshaller.JAXB_FORMATTED_OUTPUT,
				true);
			ObjectFactory factory = new ObjectFactory();

			JobConfig config = factory.createJobConfig();
			config.setPurgeInterval("3");
			// construct db info
			DbInfo dbInfo = factory.createJobConfigDbInfo();
			dbInfo.setDbtype("Oracle");
			dbInfo.setUrl("oracle:thin:localhost:orcl");
			dbInfo.setUsername("admin");
			dbInfo.setPassword("admin");
			config.setDbInfo(dbInfo);

			// construct job info
			JobInfo jobInfo = factory.createJobConfigJobInfo();
			// job info - frequency
			Frequency frequency = factory.createJobConfigJobInfoFrequency();
			frequency.setInterval("10");
			frequency.setIntervalType("WEEKLY");
			frequency.setStartTime("09:00");
			jobInfo.setFrequency(frequency);
			// job info - ObjectsComponent
			ObjectsComponent objectComponet = factory.createJobConfigJobInfoObjectsComponent();
			Object runtimeObj = factory.createObject();
			runtimeObj.setObjectName("RUNTIME");
			runtimeObj.setRetention("10");
			objectComponet.getObject().add(
				runtimeObj);
			Object buildtimeObj = factory.createObject();
			buildtimeObj.setObjectName("BUILDTIME");
			buildtimeObj.setRetention("20");
			objectComponet.getObject().add(
				buildtimeObj);
			jobInfo.setObjectsComponent(objectComponet);
			// job info - ObjectsSpecific
			ObjectsSpecific objectSpecfic = factory.createJobConfigJobInfoObjectsSpecific();
			Object tObj1 = factory.createObject();
			tObj1.setObjectName("GOOD");
			tObj1.setRetention("10");
			objectSpecfic.getObject().add(
				tObj1);
			Object tObj2 = factory.createObject();
			tObj2.setObjectName("FAT");
			tObj2.setRetention("20");
			objectSpecfic.getObject().add(
				buildtimeObj);
			jobInfo.setObjectsSpecific(objectSpecfic);

			config.setJobInfo(jobInfo);

			// marshal to file
			marshaller.marshal(
				config,
				new FileOutputStream(xmlDocument));
			// marshal to console
			marshaller.marshal(
				config,
				System.out);
		}
		catch (IOException e)
		{
			System.out.println(e.toString());
		}
		catch (JAXBException e)
		{
			System.out.println(e.toString());
		}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics