首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

几种操作 Feed 的 API 的示例及其比较 -3 XMLBeans 以及 XMLBeans API

几种操作 Feed 的 API 的示例及其比较 -3 XMLBeans 以及 XMLBeans API

XMLBeans 以及 XMLBeans API是 Apache 的另一个处理 XML 的项目,旨在提供一个直观的方式允许程序访问 XML。通过为 XML 提供类似 java 面向对象的试图,使得熟悉了面向对象的程序员倍感亲切。另外,XMLBeans 还提供了功能强大 XMLCursor, 类似于指针,用 XMLCursor 可以方便的在 XML tree 上行走。
要在程序中使用 XMLBeans, 程序需要包括 XBeans.jar. 可以从 XMLBeans 项目网站上下载。需要注意 license 的问题。清单 3 给出了用 XMLBeans API 实现的 Feed Query。
清单 3. 用 XMLBeans API 实现 Feed Query
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package xml.xbean;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;

public class XbeanFilterFeed implements main.IFilterFeed{
   
public OutputStream filter(InputStream is, String xpathExpr){
   
OutputStream os = System.out;
   
try {
  // parse input stream into XML object
  XmlObject input = XmlObject.Factory.parse(is);
   
//create output XML object
  XmlObject output = XmlObject.Factory.newInstance();
   
//generate a copy version of input
  output = input.copy();
   
//new XML cursor
  XmlCursor outputCursor = output.newCursor();
   
//declare namespace using XML Object Xpath syntax
  String expression = "declare namespace atom = 'http://www.w3.org/2005/Atom';" +
  "declare namespace row = 'http://www.ibm.com/xmlns/atom/content/datarow/1.0';";
   
//append the xpath expression after namespace declaration
  expression = expression + "atom:feed/atom:entry[not(" + xpathExpr + ")]";

  // XML cursor performs xpath evaluation
  outputCursor.selectPath(expression);
   
while(outputCursor.hasNextSelection()){
  outputCursor.toNextSelection();
  outputCursor.removeXml();
  }
  //dispose XML cursor
  outputCursor.dispose();
   
//write XML object to output Stream
  output.save(os);
   
} catch (XmlException e) {
  e.printStackTrace();
  } catch (IOException e) {
  e.printStackTrace();
  }
  return os;
  }
   
}




从程序清单 3 可以看出,用 XMLBeans API 实现的 Feed Query 的主要步骤如下:
  • XMLObject 静态方法获得 Factory,
  • 解析输入的 XML 文档创建 XMLObject 对象
  • 为创建的 XMLObject 对象创建 XMLCursor 对象用于遍历 XML。
  • 用声明式的方式定义 namespace,并与 XPath expression 一块传给 XMLCursor。
  • 执行 XPath evaluation。
  • 序列化。XMLObject 的 save 方法很方便的实现 XMLObject 的序列化。
和 Abdera 一样,XMLBeans 提供了非常友好的 API,应用程序可以很方便的根据自己的需要进行 XML 的操作。除此之外,XMLBeans 还有一些别的优点:比如:DOM 需要在内存中生成整个文档的树。如果文档非常大,DOM 就会变得对内存非常敏感,并会显著降低性能。XMLBeans 通过增量解组(incremental unmarshalling)并提供 xget 方法来访问内置的模式数据类型,取得了较好的性能。 此外,XMLBeans 还能够访问完整的 XML Infoset,对于强调元素顺序或者注释的应用程序,这一点特别有用。XMLBeans 还提供了解析 XML 实例的即时验证。XMLBeans 包括一些创新的特性,如 XML 游标和对 XQuery 的支持。
返回列表