YAML - YAML An't a Markup Lanague
P.S. YAML was originally was side to mean Yet Another Markup Language, referencing its purpose as a markup lanaguage with the yet another construct; but it was then repurposed as YAML Anit Markup Language (仍是標記語言,只是為了強調不同,YAML 是以數據設計為重點,XML以標記為重點), a recursive acronym, to distinguish its purpose as data-orinted, rather than document markup.
為什么用YAML -> 對比XML的幾點優勢
可讀性高 && 和腳本語言的交互性好 && 使用實現語言的數據類型 && 有一個一致的信息模型 && 易於實現 && 可以基於流來處理 && 表達能力強,擴展性好
YAML 語法規則 -> Structure 用空格表示 && Sequence里的項用"-"表示 && MAP 里的鍵值對用 ":"分隔
#John.yaml
name: John Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name: Jenny Smith
age 12
JYaml - > 基於Java 的YAML實現 (使用JAVA的數據類型)
JYaml 支持的Java數據類型
原始數據和封裝類 && JavaBean 兼容對象(Structure 支持)&& Collection [List, Set] (Sequence 支持)&& Map (map 支持) && Arrays (sequence 支持) && Date
#John.yaml 的Java描述
public class Person {
private String name;
private int age;
private Person sponse;
private Person[] children;
// setXXX, getXXX方法略.
}
# 添加John
Person john = new Person();
john.setAge(37);
john.setName("John Smith");
Person sponse = new Person();
sponse.setName("Jane Smith");
sponse.setAge(25);
john.setSponse(sponse);
Person[] children = {new Person(), new Person()};
children[0].setName("Jimmy Smith");
children[0].setAge(15);
children[1].setName("Jenny Smith");
children[1].setAge(12);
john.setChildren(children);
#使用JYaml 將John dump出來
File dumpfile = new File("John_dump.yaml");
Yaml.dump(john, dumpfile);
# 用JYaml 把Jone_dump.yaml load 進來
Person john2 = (Person) Yaml.loadType(dumpfile, Person.class);
JYaml 對流的處理
#把同一個John 寫10次
YamlEncoder enc = new YamlEncoder(new FileOutputStream(dumpfile)); for(int i=0; i<10; i++){ john.setAge(37+i); enc.writeObject(john); enc.flush(); } enc.close();
#依次讀出此10個對象
YamlDecoder dec = new YamlDecoder(new FileInputStream(dumpfile));
int age = 37;
while(true){
try{
john = (Person) dec.readObject();
assertEquals(age, john.getAge());
age++;
}catch(EOFException eofe){
break;
}
}
YAML 的適用范圍
a. 由於解析成本低,YAML比較適合在腳本語言中使用, 現有的語言有: Ruby, Java, Perl, Python, PHP, JavaScript & Java
b. YAML 比較適合做序列化, 因為它支持對宿主語言的直接轉化
c. 做配置文件
Note: 由於兼容性問題,不同語言間的數據流轉不建議使用YAML
YAML 存在的意義
YAML和XML不同,沒有自己的數據類型的定義,而是使用實現語言的數據類型。這一點,有可能是出奇制勝的地方,也可能是一個敗筆。如果兼容性保證的不好的話,YAML數據在不同語言間流轉會有問題。如果兼容性好的話,YAML就會成為不同語言間數據流通的橋梁。建議yaml.org設立兼容認證機制,每個語言的實現必須通過認證。
Reference -> https://www.ibm.com/developerworks/cn/xml/x-cn-yamlintro/index.html