简体   繁体   English

删除YAML文件中键值对之前的破折号

[英]Remove the dash present before the key value pair in a YAML file

It is known that the dash ( - ) in a YAML file before the key value pair is necessary to show that it is separate block(it is what I think). 众所周知,在键值对之前,YAML文件中的破折号( - )是必要的,以表明它是单独的块(这是我的想法)。 Figure 1 shows the YAML I'm generating using YamlBeans jar. 图1显示了我使用YamlBeans jar生成的YAML。

field1:
-  childfield1:
      datafield1:
         param1:
            childparam: paramvalue
         param2:
            childparam2: paramvalue
         param3:
            childparam3: paramvalue
      datafield2: value2

For my codebase can't be changed, I have to somehow create the YAMLs as shown in Figure 2 (a tab is appended in each line in yaml file) or remove the dash is removed. 对于无法更改的代码库,我必须以某种方式创建如图2所示的YAML(在yaml文件的每一行中都附加了一个选项卡),或者删除了破折号。 You can clearly observe that there are only two thin vertical lines in Figure 1 but three thin vertical lines in Figure 2 which shows the alignment of the blocks. 您可以清楚地观察到,图1中只有两条垂直细线,而图2中只有3条垂直细线,显示了块的对齐方式。

What I want to achieve is to remove that dash from the first block (at the child field) from the file. 我要实现的是从文件的第一个块(子字段)中删除该破折号。 Using a YAML file reader and writer always introduces the dash. 使用YAML文件读取器和写入器始终会引入破折号。

Glancing quick at (but admittedly not being familiar with) YamlBeans, it doesn't look like it's easy to subclass the behavior of the Emitter. 快速浏览(但不熟悉)YamlBeans,看起来很难将Emitter的行为子类化。 One option though is to generate a temporary form in memory, then manipulate the results when writing out to a file. 但是,一种选择是在内存中生成临时形式,然后在写出文件时操纵结果。 For example 例如

    // let YamlWriter write its contents to an in-memory buffer
    StringWriter temp = new StringWriter();
    YamlWriter yamlOut = new YamlWriter(temp);
    yamlOut.write(someObject);

    // then dump the in-memory buffer out to a file, manipulating lines that
    // start with a dash
    PrintWriter out = new PrintWriter(new FileWriter(new File("someoutput.dat")));
    LineNumberReader in = new LineNumberReader(new StringReader(temp.toString()));
    String line;
    while ((line = in.readLine()) != null) {
        if (line.startsWith("-")) {
            line = line.substring(1);
        }
        out.println(line);
    }

my specifics may be off, but hopefully the approach of doing simple manipulations of a temporary copy is clear enough. 我的细节可能不对,但是希望对临时副本进行简单操作的方法足够清晰。

If I were personally doing this, I'd probably write a custom subclass of java.io.Writer and do the manipulation on the fly (but i haven't gone through YamlWriter/Emitter in enough detail to provide an example on how to do that) 如果我亲自进行此操作,则可能会编写一个java.io.Writer的自定义子类,并即时进行操作(但我没有足够详细地了解过YamlWriter / Emitter来提供如何执行操作的示例那)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM