You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

264 lines
6.9 KiB

3 months ago
  1. _The following describes the old API. For the new API, see the [Tutorial](https://github.com/jbeder/yaml-cpp/wiki/Tutorial)._
  2. ## Contents ##
  3. # Basic Parsing #
  4. The parser accepts streams, not file names, so you need to first load the file. Since a YAML file can contain many documents, you can grab them one-by-one. A simple way to parse a YAML file might be:
  5. ```
  6. #include <fstream>
  7. #include "yaml-cpp/yaml.h"
  8. int main()
  9. {
  10. std::ifstream fin("test.yaml");
  11. YAML::Parser parser(fin);
  12. YAML::Node doc;
  13. while(parser.GetNextDocument(doc)) {
  14. // ...
  15. }
  16. return 0;
  17. }
  18. ```
  19. # Reading From the Document #
  20. Suppose we have a document consisting only of a scalar. We can read that scalar like this:
  21. ```
  22. YAML::Node doc; // let's say we've already parsed this document
  23. std::string scalar;
  24. doc >> scalar;
  25. std::cout << "That scalar was: " << scalar << std::endl;
  26. ```
  27. How about sequences? Let's say our document now consists only of a sequences of scalars. We can use an iterator:
  28. ```
  29. YAML::Node doc; // already parsed
  30. for(YAML::Iterator it=doc.begin();it!=doc.end();++it) {
  31. std::string scalar;
  32. *it >> scalar;
  33. std::cout << "Found scalar: " << scalar << std::endl;
  34. }
  35. ```
  36. ... or we can just loop through:
  37. ```
  38. YAML::Node doc; // already parsed
  39. for(unsigned i=0;i<doc.size();i++) {
  40. std::string scalar;
  41. doc[i] >> scalar;
  42. std::cout << "Found scalar: " << scalar << std::endl;
  43. }
  44. ```
  45. And finally maps. For now, let's say our document is a map with all keys/values being scalars. Again, we can iterate:
  46. ```
  47. YAML::Node doc; // already parsed
  48. for(YAML::Iterator it=doc.begin();it!=doc.end();++it) {
  49. std::string key, value;
  50. it.first() >> key;
  51. it.second() >> value;
  52. std::cout << "Key: " << key << ", value: " << value << std::endl;
  53. }
  54. ```
  55. Note that dereferencing a map iterator is undefined; instead, use the `first` and `second` methods to get the key and value nodes, respectively.
  56. Alternatively, we can pick off the values one-by-one, if we know the keys:
  57. ```
  58. YAML::Node doc; // already parsed
  59. std::string name;
  60. doc["name"] >> name;
  61. int age;
  62. doc["age"] >> age;
  63. std::cout << "Found entry with name '" << name << "' and age '" << age << "'\n";
  64. ```
  65. One thing to be keep in mind: reading a map by key (as immediately above) requires looping through all entries until we find the right key, which is an O(n) operation. So if you're reading the entire map this way, it'll be O(n^2). For small n, this isn't a big deal, but I wouldn't recommend reading maps with a very large number of entries (>100, say) this way.
  66. ## Optional Keys ##
  67. If you try to access a key that doesn't exist, `yaml-cpp` throws an exception (see [When Something Goes Wrong](https://github.com/jbeder/yaml-cpp/wiki/How-To-Parse-A-Document-(Old-API)#When_Something_Goes_Wrong). If you have optional keys, it's often easier to use `FindValue` instead of `operator[]`:
  68. ```
  69. YAML::Node doc; // already parsed
  70. if(const YAML::Node *pName = doc.FindValue("name")) {
  71. std::string name;
  72. *pName >> name;
  73. std::cout << "Key 'name' exists, with value '" << name << "'\n";
  74. } else {
  75. std::cout << "Key 'name' doesn't exist\n";
  76. }
  77. ```
  78. # Getting More Complicated #
  79. The above three methods can be combined to read from an arbitrary document. But we can make life a lot easier. Suppose we're reading 3-vectors (i.e., vectors with three components), so we've got a structure looking like this:
  80. ```
  81. struct Vec3 {
  82. float x, y, z;
  83. };
  84. ```
  85. We can read this in one operation by overloading the extraction (>>) operator:
  86. ```
  87. void operator >> (const YAML::Node& node, Vec3& v)
  88. {
  89. node[0] >> v.x;
  90. node[1] >> v.y;
  91. node[2] >> v.z;
  92. }
  93. // now it's a piece of cake to read it
  94. YAML::Node doc; // already parsed
  95. Vec3 v;
  96. doc >> v;
  97. std::cout << "Here's the vector: (" << v.x << ", " << v.y << ", " << v.z << ")\n";
  98. ```
  99. # A Complete Example #
  100. Here's a complete example of how to parse a complex YAML file:
  101. `monsters.yaml`
  102. ```
  103. - name: Ogre
  104. position: [0, 5, 0]
  105. powers:
  106. - name: Club
  107. damage: 10
  108. - name: Fist
  109. damage: 8
  110. - name: Dragon
  111. position: [1, 0, 10]
  112. powers:
  113. - name: Fire Breath
  114. damage: 25
  115. - name: Claws
  116. damage: 15
  117. - name: Wizard
  118. position: [5, -3, 0]
  119. powers:
  120. - name: Acid Rain
  121. damage: 50
  122. - name: Staff
  123. damage: 3
  124. ```
  125. `main.cpp`
  126. ```
  127. #include "yaml-cpp/yaml.h"
  128. #include <iostream>
  129. #include <fstream>
  130. #include <string>
  131. #include <vector>
  132. // our data types
  133. struct Vec3 {
  134. float x, y, z;
  135. };
  136. struct Power {
  137. std::string name;
  138. int damage;
  139. };
  140. struct Monster {
  141. std::string name;
  142. Vec3 position;
  143. std::vector <Power> powers;
  144. };
  145. // now the extraction operators for these types
  146. void operator >> (const YAML::Node& node, Vec3& v) {
  147. node[0] >> v.x;
  148. node[1] >> v.y;
  149. node[2] >> v.z;
  150. }
  151. void operator >> (const YAML::Node& node, Power& power) {
  152. node["name"] >> power.name;
  153. node["damage"] >> power.damage;
  154. }
  155. void operator >> (const YAML::Node& node, Monster& monster) {
  156. node["name"] >> monster.name;
  157. node["position"] >> monster.position;
  158. const YAML::Node& powers = node["powers"];
  159. for(unsigned i=0;i<powers.size();i++) {
  160. Power power;
  161. powers[i] >> power;
  162. monster.powers.push_back(power);
  163. }
  164. }
  165. int main()
  166. {
  167. std::ifstream fin("monsters.yaml");
  168. YAML::Parser parser(fin);
  169. YAML::Node doc;
  170. parser.GetNextDocument(doc);
  171. for(unsigned i=0;i<doc.size();i++) {
  172. Monster monster;
  173. doc[i] >> monster;
  174. std::cout << monster.name << "\n";
  175. }
  176. return 0;
  177. }
  178. ```
  179. # When Something Goes Wrong #
  180. ... we throw an exception (all exceptions are derived from `YAML::Exception`). If there's a parsing exception (i.e., a malformed YAML document), we throw a `YAML::ParserException`:
  181. ```
  182. try {
  183. std::ifstream fin("test.yaml");
  184. YAML::Parser parser(fin);
  185. YAML::Node doc;
  186. parser.GetNextDocument(doc);
  187. // do stuff
  188. } catch(YAML::ParserException& e) {
  189. std::cout << e.what() << "\n";
  190. }
  191. ```
  192. If you make a programming error (say, trying to read a scalar from a sequence node, or grabbing a key that doesn't exist), we throw some kind of `YAML::RepresentationException`. To prevent this, you can check what kind of node something is:
  193. ```
  194. YAML::Node node;
  195. YAML::NodeType::value type = node.Type(); // should be:
  196. // YAML::NodeType::Null
  197. // YAML::NodeType::Scalar
  198. // YAML::NodeType::Sequence
  199. // YAML::NodeType::Map
  200. ```
  201. # Note about copying `YAML::Node` #
  202. Currently `YAML::Node` is non-copyable, so you need to do something like
  203. ```
  204. const YAML::Node& node = doc["whatever"];
  205. ```
  206. This is intended behavior. If you want to copy a node, use the `Clone` function:
  207. ```
  208. std::auto_ptr<YAML::Node> pCopy = myOtherNode.Clone();
  209. ```
  210. The intent is that if you'd like to keep a `YAML::Node` around for longer than the document will stay in scope, you can clone it and store it as long as you like.