/// <summary> /// Gets a scalar value identified by its key /// </summary> /// <param name="parent">Parent node</param> /// <param name="key">Key of the value</param> /// <param name="errorMessage">Error message if the key does not exists</param> /// <returns>Returns the scalar value</returns> public string GetScalarValue(YamlNode parent, string key, string errorMessage = null) { Contract.Requires(parent != null); Contract.Requires(key != null); Contract.Ensures(Contract.Result<string>() != null); try { var mapping = (YamlMappingNode)parent; var pairs = EnumerateNodesOf(mapping); var keyNode = new YamlScalarNode(key); foreach (var pair in pairs) { if (keyNode.Equals(pair.Key)) { if (pair.Value is YamlScalarNode) { var v = ((YamlScalarNode) pair.Value).Value; if (v != null) return v; } throw new InvalidSpecificationException(errorMessage ?? String.Format("No value for key {0}", key)); } } throw new InvalidSpecificationException(String.Format("Parent has no child with key {0}", key)); } catch (Exception ex) { throw new InvalidSpecificationException(errorMessage ?? ex.Message, ex); } }
/// <summary> /// Gets an optional scalar value identified by its key /// </summary> /// <param name="parent">Parent node</param> /// <param name="key">Key of the value</param> /// <param name="defaultValue">Default value to be used if the key is not found in parent</param> /// <returns>Returns either the scalar value read from the parent node, or the default value.</returns> public string GetOptionalScalarValue(YamlNode parent, string key, string defaultValue) { Contract.Requires(parent != null); Contract.Requires(key != null); Contract.Ensures(Contract.Result<string>() != null || Contract.Result<string>() == defaultValue); var mapping = parent as YamlMappingNode; if (mapping != null) { var pairs = EnumerateNodesOf(mapping); var keyNode = new YamlScalarNode(key); foreach (var pair in pairs) { if (keyNode.Equals(pair.Key) && pair.Value is YamlScalarNode) return ((YamlScalarNode)pair.Value).Value; } } return defaultValue; }