我正在寻找一种方法来解析 yaml 文件并更改每个字符串,然后在不更改原始文件结构的情况下保存文件。在我看来,我不应该为此使用正则表达式,而应该使用某种 yaml 解析器。 示例 yaml 输入波纹管:
receipt: Oz-Ware Purchase Invoice
date: 2007-08-06
customer:
given: Dorothy
items:
- part_no: A4786
descrip: Water Bucket (Filled)
- part_no: E1628
descrip: High Heeled "Ruby" Slippers
size: 8
bill-to: &id001
street: |
123 Tornado Alley
Suite 16
city: East Centerville
state: KS
ship-to: *id001
specialDelivery: >
Follow the Yellow Brick
Road to the Emerald City.
...
期望的输出:
receipt: ###Oz-Ware Purchase Invoice###
date: ###2007-08-06###
customer:
given: ###Dorothy###
items:
- part_no: ###A4786###
descrip: ###Water Bucket (Filled)###
- part_no: ###E1628###
descrip: ###High Heeled "Ruby" Slippers###
size: ###8###
bill-to: ###&id001###
street: |
###123 Tornado Alley
Suite 16###
city: ###East Centerville###
state: ###KS###
ship-to: ###*id001###
specialDelivery: >
###Follow the Yellow Brick
Road to the Emerald City.###
...
是否有一个好的 yaml 解析器可以处理复杂的 yaml 文件、更改字符串并在不影响文档结构的情况下保存数据?也许你有其他想法如何解决这个问题。基本上我想遍历文档顶部的每个字符串并对字符串进行一些修改。 任何提示表示赞赏。
最佳答案
YAML 规范有 this to say :
In the representation model, mapping keys do not have an order. To serialize a mapping, it is necessary to impose an ordering on its keys. This order is a serialization detail and should not be used when composing the representation graph (and hence for the preservation of application data). In every case where node order is significant, a sequence must be used. For example, an ordered mapping can be represented as a sequence of mappings, where each mapping is a single key: value pair. YAML provides convenient compact notation for this case.
所以你真的不应该期望 YAML 在加载和保存文档时保持任何顺序。
话虽如此,我完全理解您的想法。由于 YAML 文档是为人类准备的,因此保持一定的顺序绝对有帮助。不幸的是,由于规范,大多数实现将使用无序数据结构来表示键/值映射。在 C# 和 Python 中,这将是一个字典;和字典是没有顺序的设计。
但是 C# 和 Python 确实有有序的字典类型,OrderedDictionary
和 OrderedDict
,至少对于 Python 而言,过去曾有一些努力使用有序字典来维护键顺序:
!!omap
type是一个特殊的有序映射。 PyYAML 支持它。- PyYAML ticket 29谈论可能包含一个
OrderedLoader
。还有一个使用 YAML 构造函数的简短解决方法 in between ,以及加载程序的可能实现 at the end . - PyYAML ticket 161有一个recipe它也提供此功能。
- 最后,有 this other Stack Overflow question包括将 YAML 加载到
OrderedDict
中。
那是 Python 方面;我相信 C# 实现也有类似的努力。
关于C# 解析和更改 yaml 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30492841/