使用XMLBeans绑定XML-java数据

http://tech.ddvip.com   2007年09月02日    社区交流

内容摘要:XMLBeans提供了底层XML数据的对象视图,同时还能访问原始的XML信息集合。通过递增的解除封送xml数据和高效的访问XML 模式内置数据类型的方法,XMLBeans交付了较好的性能……

  为了获得输入XML文档的内容,我们先检查XmlObject.Factory.parse()返回的对象的文档类型,然后把返回的对象转化为相应的文档类型,以供稍后处理。另一段有趣的代码是最后的else代码块,它将处理格式良好的XML文档不符合weather_latlong.xsd模式的情况。

  创建一个新的XML文档

  下面的一小段latlong_marshal.java代码阐述了如何使用XMLBeans生成的类创建一个包含经纬度信息的新xml实例文档。

LatlongDocument latLongDoc;
LatlongDocument.Latlong latLongElement;
XmlOptions xmlOptions;
// LatlongDocument.Factory.newInstance() creates
// and returns a LatlongDocument object.
latLongDoc= LatlongDocument.Factory.newInstance();
// addNewLatlong() method is called on the
// document object to create and add a new
// LatLong Element to document.
latLongElement = latLongDoc.addNewLatlong();

  LatlongDocument.Factory.newInstance()创建了一个LatlongDocument对象并且返回该对象。随后对文档对象调用addNewLatlong()方法创建并向文档增加一个新的LatLong元素。

  要向LatLong元素添加数据, 简单调用latLongElement的相应的Set方法即可,它将直接映射模式中定义的的元素和属性名称。

  latLongElement.setZipcode("91023");
  latLongElement.setLatitude("33.8792");
  latLongElement.setLongitude("117.8974");

  最后的代码段将LatLong元素的当前状态写到了标准的输出流中。

xmlOptions = new XmlOptions();
// Requests use of whitespace for easier reading
xmlOptions.setSavePrettyPrint();
// Requests that nested levels of the xml
// document to be indented by multiple of 4
// whitespace characters
xmlOptions.setSavePrettyPrintIndent(4);
String xmlStr = latLongDoc.xmlText(xmlOptions);
// Writes the current state of the LatLong
// element to a standard output stream
System.out.println("XML Instance Document is : "
 + "
" + xmlStr );

来源:Dev2Dev    作者:Hetal C. Shah    责编:豆豆技术应用

正在加载评论...