9

7月

在Web 2.0 时代,XML格式由于AJAX的风行以及RSS的普及而异军突起。不过随着Python和Ruby On Rails的走红,以及各种API的发布,YAML,JSON也逐渐成名。此次,Google推出了Protocol Buffers,是想让广大编程者方便地使用Google网络传输数据的格式。



什么是Protocol Buffers?

这是Protocol Buffers主页上的一段代码:

message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;

enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
} message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}

repeated PhoneNumber phone = 4;
}

而Protocol Buffers的作用,就是将以上格式的数据类型,自动生成Java, Python, and C++的代码,然后以下一系列代码就可以直接调用了:(C++中)

Person person;
person.set_name("John Doe");
person.set_id(1234);
person.set_email("jdoe@example.com");
fstream output("myfile", ios::out | ios::binary);
person.SerializeToOstream(&output); fstream input("myfile", ios::in | ios::binary);
Person person;
person.ParseFromIstream(&input);
cout << "Name: " << person.name() << endl;
cout << "E-mail: " << person.email() << endl;

相信所有C++编程者都为定义set,get之类的函数感到烦人过吧,而Google做的就是帮助你省去这些麻烦,构造更利于网络传输的数据结构。

与XML的比较 优势

更简单
比XML小3到10倍体积
比XML快20到100倍
更不容易引起歧义
自动生成可编程的类代码
比较:
cout << "Name: " << person.name() << endl;

cout << "E-mail: " << person.email() << endl;
cout << "Name: "
       << person.getElementsByTagName("name")->item(0)->innerText()
       << endl;
cout << "E-mail: "
       << person.getElementsByTagName("email")->item(0)->innerText()
       << endl; 劣势

没有层次,所以无法和HTML标记语言打交道
如果没有message的定义,根本无法知道message的意思,而XML是自解释型的。
Protocol Buffer主页    Protocol Buffer下载
评论(1) | 引用(0) | 阅读(362)
start2002
2008-7-18 12:51
俺完全看不懂
真是高人。。
分页: 1/1 第一页 1 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]