2

I need to read a YAML file and then convert it to HTML file. I tried using YAMLDOTNET and C#.

This is an example of the YAML file;

component1:
       kbName              : KB210006
       grayVersion         : 15.2.9.0013
       greenVersion        : null
       state               : No Change
component2:
       kbName              : KB200255
       grayVersion         : 15.2.8.434
       greenVersion        : null
       state               : No Change

Can this be done using YAMLDONET and C#?

Thanks!

Oo'-
  • 203
  • 6
  • 22
joe
  • 21
  • 1

1 Answers1

2

First of all, You need to deserialize the YAML format to Correct Object Format. The YAMLDOTNET Github repository contains a clear and well-defined example of how to deserialize a YAML format to an object. I've provided an example to follow and converted the YAML format to an HTML table.

using System;
using System.Collections.Generic;
using YamlDotNet.Serialization;

namespace YAML_TO_HTML
{
    class Program
    {
        static void Main(string[] args)
        {
            var yml = @"
component1:
       kbName              : KB210006
       grayVersion         : 15.2.9.0013
       greenVersion        : null
       state               : No Change
component2:
       kbName              : KB200255
       grayVersion         : 15.2.8.434
       greenVersion        : null
       state               : No Change
";

            var deserializer = new DeserializerBuilder().Build();
            //yml contains a string containing your YAML
            var p = deserializer.Deserialize<Dictionary<string, data_model>>(yml);
            string table_format = "    <tr>\n        <td>{0}</td>\n        <td>{1}</td>\n        <td>{2}</td>\n        <td>{3}</td>\n        <td>{4}</td>\n    </tr>";
            string html = "<table>\n";
            foreach (KeyValuePair<string, data_model> component in p)
            {
                html = html + String.Format(table_format,
                    component.Key,
                    component.Value.kbName,
                    component.Value.grayVersion,
                    component.Value.greenVersion,
                    component.Value.state) + "\n";
            }
            html = html + "</table>\n";
            Console.WriteLine(html);
        }
    }

    public class data_model
    {
        public string kbName { get; set; }
        public string grayVersion { get; set; }
        public string greenVersion { get; set; }
        public string state { get; set; }
    }
}

The output is:

<table>
    <tr>
        <td>component1</td>
        <td>KB210006</td>
        <td>15.2.9.0013</td>
        <td></td>
        <td>No Change</td>
    </tr>
    <tr>
        <td>component2</td>
        <td>KB200255</td>
        <td>15.2.8.434</td>
        <td></td>
        <td>No Change</td>
    </tr>
</table>
A Farmanbar
  • 4,381
  • 5
  • 24
  • 42