你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Linux开发
使用XMLBeans绑定XML-java数据(3)
 
对于全局元素和属性,XMLBeans 模式编译器将分别生成名称以Document和Attribute结尾的接口。

  对于在另一个元素或类型的声明中局部声明的命名类型,XMLBeans会在元素或类型接口中生成一个内部接口,形成嵌套结构。

  考虑下面的employee.xsd 模式列表。

<?xml version="1.0" encoding="UTF-8"?>
<!-- This XML Schema describes Employee's
  Jobstatus -->
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="Employee">
 <xsd:sequence>
  <xsd:element name="Jobstatus">
  <xsd:simpleType>
   <xsd:restriction base="xsd:NMTOKEN">
   <xsd:enumeration value="fullTime"/>
   <xsd:enumeration value="hourly"/>
   </xsd:restriction>
  </xsd:simpleType>
  </xsd:element>
 </xsd:sequence>
</xsd:complexType>
</xsd:schema>

  因此,XMLBeans在元素Employee的接口中生成了一个内部接口Jobstatus,嵌套在了Employee接口中。

public interface Employee
 extends org.apache.xmlbeans.XmlObject
{
...
public interface Jobstatus
  extends org.apache.xmlbeans.XmlNMTOKEN
 {
 }
}

  Employee类在这里扩展了org.apache.xmlbeans.XmlObject,这是所有XMLBeans类型的基础接口。所有的内置模式类型,用户定义类型和派生的模式类型都从XmlObject中继承而来。

使用XMLBeans类解除封送XML文件

  下面的一小段weather_unmarshal.java代码阐明了怎样使用XMLBeans类从weatherInput.xml.文件的XML文档中获取天气信息。

String filePath = "weatherInput.xml";
java.io.File inputXMLFile =
new java.io.File(filePath);
// Parse XML Document.
WeatherDocument weatherDoc =
WeatherDocument.Factory.parse(inputXMLFile);
// Get object reference of root element Weather.
WeatherDocument.Weather weatherElement =
weatherDoc.getWeather();

  通过调用WeatherDocument.Factory.parse(File)方法来解析XML文件,该方法返回一个WeatherDocument对象。随后对weatherDocument对象调用getWeather()方法来获取根元素Weather的对象引用。

  要获得Weather元素的内容,简单调用weatherElement的相应的get方法,它将直接映射模式定义的元素和属性名称:

// Call the appropriate 'get' methods of
// weatherElement that
// directly map to the element and attribute names
// defined in the schema.
Calendar timeStamp = weatherElement.getDatetime();
System.out.println("Weather details of zipcode "
+ weatherElement.getZipcode() + " at "
+ timeStamp);
System.out.println("Temperature is "
+ weatherElement.getTemperature());
System.out.println("Humidity is "
+ weatherElement.getHumidity());
System.out.println("Visibility is "
+ weatherElement.getVisibility());

(编辑:aniston)

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089