对于全局元素和属性,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)
|