YAML - 簡介

YAML - YAML An't a Markup Lanaguehtml

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. ide

爲何用YAML -> 對比XML的幾點優點ui

可讀性高 && 和腳本語言的交互性好 && 使用實現語言的數據類型 && 有一個一致的信息模型 && 易於實現 && 能夠基於流來處理 && 表達能力強,擴展性好spa

YAML 語法規則 -> Structure 用空格表示 && Sequence裏的項用"-"表示 && MAP 裏的鍵值對用 ":"分隔設計

                          #John.yaml                           code

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的數據類型)xml

JYaml 支持的Java數據類型 htm

    原始數據和封裝類 && JavaBean 兼容對象(Structure 支持)&& Collection [List, Set] (Sequence 支持)&& Map (map 支持) && Arrays (sequence 支持) && Date 對象

    #John.yaml 的Java描述 blog

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

相關文章
相關標籤/搜索