C# 解析和更改 yaml 中的字符串

标签 c# python parsing yaml yamldotnet

我正在寻找一种方法来解析 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 确实有有序的字典类型,OrderedDictionaryOrderedDict ,至少对于 Python 而言,过去曾有一些努力使用有序字典来维护键顺序:

那是 Python 方面;我相信 C# 实现也有类似的努力。

关于C# 解析和更改 yaml 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30492841/

相关文章:

java - 如何解析不规则使用引号的 CSV 文件?

php - 在 PHP 中拆分嵌套括号的正确方法,例如 "root[one[a,b,c],two[d,e,f]]"到数组?

c# - 如何实现每小时运行一次但也可以从 .aspx 页面触发的作业?

c# - NHibernate session 管理?

python - 合并两个双端队列 O(1)

python 单元测试,我需要从 tests/__init__.py 导入吗?

python - 在 AngularJS 指令中从 templateURL 加载 html(在 django 应用程序中)

c++ - 提升精神 x3 int32 | double_ 无法解析 double

c# - 使用绑定(bind)而不是循环检查/取消选中所有复选框?

c# - 获取表中的外键