使用XMLBeans绑定XML-java数据
http://tech.ddvip.com 2007年09月02日 社区交流
内容摘要:XMLBeans提供了底层XML数据的对象视图,同时还能访问原始的XML信息集合。通过递增的解除封送xml数据和高效的访问XML 模式内置数据类型的方法,XMLBeans交付了较好的性能……
输出的结果是:
Weatherdetailsofzipcode92834-2345at2003-11-13T05:29:27-03:01
Temperatureis85.3
Humidityis50.0
Visibilityis5.5
模式声明多个全局元素时如何解除封送
在上面的例子中,我们假设输入XML文档始终包含天气信息。然而,在实际中,由于weather_latlong.xsd文件通过声明两个全局元素(Weather和Latlong)同时描述了二者的详细信息,因此输入XML文档中可能包含天气信息也可能包含经纬度信息。。
有两种方法可以解析一个xml文档并将其绑定到相应XMLBeans类型的实例。在上述的例子中,我们用WeatherDocument.Factory.parse()方法解析XML文档。另外一种方式是使用XMLBeans内置的XmlObject类。
下面的一小段weather_unmarshal_xmlObject.java代码阐述了怎样使用XmlObject类获取xml实例文档中包含的天气和经纬度信息。
public static void main(String args[]) {
try {
if (args.length < 1 ) {
System.out.println("Usage : java "
+"weather_unmarshal_xmlObject <<InputFilePath>>");
return;
}
String filePath = args[0];
java.io.File inputXMLFile
= new java.io.File(filePath);
XmlObject xmlObjExpected =
XmlObject.Factory.parse(inputXMLFile);
// Check document type of the object returned by
// the call to XmlObject.Factory.parse() method.
// If type of object returned is of
//noNamespace.WeatherDocument, then input xml
//document carries weather details of a location.
if (xmlObjExpected instanceof
noNamespace.WeatherDocument) {
WeatherDocument weatherDoc =
(noNamespace.WeatherDocument)xmlObjExpected;
WeatherDocument.Weather weatherElement =
weatherDoc.getWeather();
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());
// else if type of object returned is of
// noNamespace.LatlongDocument, then input xml
//document carries latlong details of a location.
} else if(xmlObjExpected instanceof
noNamespace.LatlongDocument) {
LatlongDocument latLongDoc =
(noNamespace.LatlongDocument)xmlObjExpected;
LatlongDocument.Latlong latLongElement =
latLongDoc.getLatlong();
System.out.println
("Latlong details of zipcode "
+ latLongElement.getZipcode() + " :
");
System.out.println("Latitude is "
+ latLongElement.getLatitude());
System.out.println("Longitude is "
+ latLongElement.getLongitude());
// else input xml document is well formed , but
// doesn't conform to weather_latlong.xsd schema
// file.
} else {
System.out.println("Input xml document "
+ "doesn't conform to weather_latlong.xsd");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
来源:Dev2Dev 作者:Hetal C. Shah 责编:豆豆技术应用