YAML – 节点属性
YAML - 节点属性:锚点与标签
Section titled “YAML - 节点属性:锚点与标签”在 YAML 中,每一块数据(无论是标量(scalar)、序列(sequence)还是映射(mapping))在底层图结构中都表示为一个节点(node)。每个节点都可以拥有属性(properties),主要是锚点(anchors)和标签(tags),它们提供额外的信息或功能。这些属性可以是显式指定的,也可以由 YAML 处理器(processor)推断出来。
节点锚点(&)和别名(*)
Section titled “节点锚点(&)和别名(*)”锚点和别名是 YAML 用于数据复用的强大特性,它提倡 DRY(Don’t Repeat Yourself - 不要重复自己)原则。锚点(&anchor_name)用一个名称标记一个节点,而别名(*anchor_name)引用这个已命名的节点,有效地将其内容插入到别名所在的位置。
YAML 处理器会通过将别名替换为锚点节点的内容来解析别名。解析后,锚点名称本身不再是数据模型(data model)的一部分,尽管某些工具可能会保留它以便进行往返转换(round-tripping)。
# Example of an anchor and aliasdefault_settings: &common_config timeout: 30 retries: 3
service_a_config: <<: *common_config # Merge common_config (using an alias) specific_setting: value_a
service_b_config: <<: *common_config # Merge common_config again timeout: 60 # Override timeout from common_config specific_setting: value_b
# Parsed representation (conceptual)# service_a_config:# timeout: 30# retries: 3# specific_setting: value_a# service_b_config:# timeout: 60# retries: 3# specific_setting: value_b在上面的示例中,&common_config 锚定了默认设置。然后,*common_config 被用作合并键(merge key)(<<:)中的别名,以便将这些设置包含在 service_a_config 和 service_b_config 中。
节点标签(!)
Section titled “节点标签(!)”标签指定节点的数据类型(data type)。YAML 支持丰富的标记系统,既允许使用标准类型(如整数、字符串、布尔值),也允许使用自定义的、应用特定的类型。标签通过感叹号(!)指示。
标签有不同的形式:
- 核心/模式标签(Core/Schema Tags)(
!!tag_name): 双感叹号通常表示由标准 YAML 模式(schema)定义的类型(例如,!!str表示字符串,!!int表示整数,!!map表示映射,!!seq表示序列)。通常,这些类型是推断(inferred)出来的,不需要显式标记。 - 应用特定/本地标签(Application-Specific/Local Tags)(
!local_tag): 单个感叹号后跟一个名称表示用户定义的或应用特定的类型。这些标签的解释取决于处理 YAML 的应用程序。 - 全局 URI 标签(Global URI Tags)(
!tag:uri…): 标签也可以指定为 URI(统一资源标识符),以确保全局唯一性,例如!tag:yaml.org,2002:str。
# Example of node tags
# Inferred types (Core Schema often handles these implicitly)count: 123 # Likely !!intname: Alice # Likely !!stris_active: true # Likely !!bool
# Explicit taggingexplicit_string: !!str 42explicit_integer: !!int "42"
# Custom application tagmy_object: !<myapp/user> username: bob email: bob@example.com
# Another custom tag formcoordinates: !point { x: 10, y: 20 }标签指示 YAML 解析器(parser)如何构建原生的数据对象。对于自定义标签,应用程序需要提供相应的逻辑来处理它们。
节点内容(Node Content)
Section titled “节点内容(Node Content)”节点的内容(content)是其实际的数据值。它可以是标量(如字符串或数字)、序列(列表),或映射(字典/对象)。节点内容可以用块状风格(block style)(使用缩进表示结构)或流式风格(flow style)(内联,使用 [] 表示序列,{} 表示映射)来表示。
# Example of node content styles
# Block style mappingblock_map: key1: value1 key2: value2
# Flow style mappingflow_map: {key1: value1, key2: value2}
# Block style sequenceblock_seq: - item1 - item2
# Flow style sequenceflow_seq: [item1, item2]
# Scalar contentscalar_content: This is a string.理解节点属性(锚点、标签)和内容风格(块状、流式)对于有效利用 YAML 的表达能力来表示数据至关重要。