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