在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的比较 优势
比较:
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下载
原文地址: Google推出Protocol Buffers:争夺网络时代数据格式