---
title: "Google推出Protocol Buffers:争夺网络时代数据格式"
author: "ranfow"
date: "2008-07-08T18:37:22Z"
tags: []
slug: "google-protocol-buffers"
draft: false
lastmod: "2008-07-08T18:37:22Z"
id: 212839
url: "https://ranfow.iteye.com/blog/212839"
---

在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 &lt;&lt; "Name: " &lt;&lt; person.name() &lt;&lt; endl;  
cout &lt;&lt; "E-mail: " &lt;&lt; person.email() &lt;&lt; endl;

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

与XML的比较 优势

更简单

比XML小3到10倍体积

比XML快20到100倍

更不容易引起歧义

自动生成可编程的类代码

比较：  
cout &lt;&lt; "Name: " &lt;&lt; person.name() &lt;&lt; endl;

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

没有层次，所以无法和HTML标记语言打交道

如果没有message的定义，根本无法知道message的意思，而XML是自解释型的。

[Protocol Buffer主页](http://code.google.com/apis/protocolbuffers/docs/overview.html)     [Protocol Buffer下载](http://code.google.com/p/protobuf/downloads/)

[原文地址：](http://code.google.com/p/protobuf/downloads/) [Google推出Protocol Buffers：争夺网络时代数据格式](http://www.kangye.org/google-releases-protocol-buffers/)