📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

 
(同じ利用者による、間の2版が非表示)
62行目: 62行目:
上記セクションの要素を組み合わせて、より複雑な構造を作成することができる。<br>
上記セクションの要素を組み合わせて、より複雑な構造を作成することができる。<br>
  <syntaxhighlight lang="yaml">
  <syntaxhighlight lang="yaml">
# sample.yamlファイル
  company:
  company:
   name: Tech Solutions Inc.
   name: Tech Solutions Inc.
85行目: 87行目:
  </syntaxhighlight>
  </syntaxhighlight>
<br>
<br>
==== データの再利用 ====
==== データの再利用 ====
YAMLファイルでは、アンカー (<code>&</code>) と エイリアス (<code>*</code>) を使用して、データの再利用が可能である。<br>
YAMLファイルでは、アンカー (<code>&</code>) と エイリアス (<code>*</code>) を使用して、データの再利用が可能である。<br>
329行目: 332行目:
     }
     }
  }
  }
</syntaxhighlight>
<br>
==== YAMLファイルの書き込み ====
以下の例では、YamlDotNetライブラリを使用して、指定されたYAMLファイルを非同期で書き込んでいる。<br>
<br>
# CreateCompanyDataメソッドは、YAMLに変換するためのデータ構造を生成する。
#: ネストされたDictionaryとListを使用して、YAMLの階層構造を表現している。
#: これにより、複雑なYAML構造を柔軟に生成する。
#: <br>
# WriteYamlFileAsyncメソッドは、データをYAMLに変換して、ファイルに非同期で書き込む。
#: SerializerBuilderを使用してYAMLシリアライザを設定する。
#: ここでは、CamelCaseNamingConventionを使用しているが、必要に応じて変更可能である。
#: SerializeメソッドでデータをYAML文字列に変換する。
<br>
<syntaxhighlight lang="yaml">
# 書き込むYAMLファイル
company:
  name: Tech Solutions Inc.
  founded: 2010
  employees:
    - name: Alice Johnson
      position: CEO
      skills:
        - leadership
        - strategic planning
    - name: Bob Williams
      position: CTO
      skills:
        - programming
        - system architecture
  offices:
    headquarters:
      address: 123 Main St, Techville
      phone: 555-1234
    branch:
      address: 456 Innovation Ave, Codetown
      phone: 555-5678
</syntaxhighlight>
<br>
<syntaxhighlight lang="c#">
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
class Program
{
    static async Task Main(string[] args)
    {
      string filePath = "sample.yaml"; // 書き込むYAMLファイルのパス
      try
      {
          // 会社データを作成
          var companyData = CreateCompanyData();
          // YAMLファイルを非同期で書き込む
          await WriteYamlFileAsync(filePath, companyData);
      }
      catch (Exception ex)
      {
          Console.WriteLine($"エラーが発生: {ex.Message}");
      }
    }
    // companyデータを作成
    static Dictionary<string, object> CreateCompanyData()
    {
      return new Dictionary<string, object>
      {
          ["company"] = new Dictionary<string, object>
          {
            ["name"] = "Tech Solutions Inc.",
            ["founded"] = 2010,
            ["employees"] = new List<Dictionary<string, object>>
            {
                new Dictionary<string, object>
                {
                  ["name"] = "Alice Johnson",
                  ["position"] = "CEO",
                  ["skills"] = new List<string> { "leadership", "strategic planning" }
                },
                new Dictionary<string, object>
                {
                  ["name"] = "Bob Williams",
                  ["position"] = "CTO",
                  ["skills"] = new List<string> { "programming", "system architecture" }
                }
            },
            ["offices"] = new Dictionary<string, object>
            {
                ["headquarters"] = new Dictionary<string, string>
                {
                  ["address"] = "123 Main St, Techville",
                  ["phone"] = "555-1234"
                },
                ["branch"] = new Dictionary<string, string>
                {
                  ["address"] = "456 Innovation Ave, Codetown",
                  ["phone"] = "555-5678"
                }
            }
          }
      };
    }
    // YAMLファイルを非同期で書き込む
    static async Task WriteYamlFileAsync(string filePath, Dictionary<string, object> data)
    {
      // YAMLシリアライザの設定
      var serializer = new SerializerBuilder()
                            .WithNamingConvention(CamelCaseNamingConvention.Instance)
                            .Build();
      // YAMLにシリアライズ
      var yaml = serializer.Serialize(data);
      // ファイルに非同期で書き込み
      await File.WriteAllTextAsync(filePath, yaml);
    }
}
</syntaxhighlight>
<br>
==== YAMLファイルの修正 ====
以下の例では、YamlDotNetライブラリを使用して、指定されたYAMLファイルを非同期で修正している。<br>
<br>
YAMLファイルにおいて、修正する箇所を以下に示す。<br>
*
*
*
<br>
# ReadYamlFileAsyncメソッド
#: YAMLファイルを非同期で読み込む。
#: DeserializerBuilderを使用して、YAMLデータをDictionary<string, object>型にデシリアライズする。
#: CamelCaseNamingConventionを使用して、YAMLのキーをC#のプロパティ名に合わせている。
#: <br>
# ModifyCompanyDataメソッド
#: LINQのFirstOrDefaultメソッドを使用して、特定の従業員を検索する。
#: <br>
#: Alice Johnsonのskillに"Hardware Develop"を追加する。
#: Bob Williamsのpositionを"COO"に変更する。
#: 新しい従業員"Taro Yamada"を追加する。
#: <br>
# WriteYamlFileAsyncメソッド
#: 修正されたデータを再度YAMLフォーマットにシリアライズする。
#: File.WriteAllTextAsyncを使用して、YAML文字列をファイルに非同期で書き込む。
<br>
<syntaxhighlight lang="yaml">
# 変更前のYAMLファイル
company:
  name: Tech Solutions Inc.
  founded: 2010
  employees:
    - name: Alice Johnson
      position: CEO
      skills:
        - leadership
        - strategic planning
    - name: Bob Williams
      position: CTO
      skills:
        - programming
        - system architecture
  offices:
    headquarters:
      address: 123 Main St, Techville
      phone: 555-1234
    branch:
      address: 456 Innovation Ave, Codetown
      phone: 555-5678
</syntaxhighlight>
<br>
<syntaxhighlight lang="c#">
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
class Program
{
    static async Task Main(string[] args)
    {
      string filePath = "sample.yaml";  // 修正するYAMLファイルのパス
      try
      {
          // YAMLファイルを非同期で読み込む
          var companyData = await ReadYamlFileAsync(filePath);
          // データを修正
          ModifyCompanyData(companyData);
          // 修正したデータを非同期で書き込む
          await WriteYamlFileAsync(filePath, companyData);
      }
      catch (Exception ex)
      {
          Console.WriteLine($"エラーが発生: {ex.Message}");
      }
    }
    // YAMLファイルを非同期で読み込む
    static async Task<Dictionary<string, object>> ReadYamlFileAsync(string filePath)
    {
      var deserializer = new DeserializerBuilder()
                              .WithNamingConvention(CamelCaseNamingConvention.Instance)
                              .Build();
      using (var reader = new StreamReader(filePath))
      {
          var yaml = await reader.ReadToEndAsync();
          return deserializer.Deserialize<Dictionary<string, object>>(yaml);
      }
    }
    // 会社データを修正
    static void ModifyCompanyData(Dictionary<string, object> data)
    {
      var company = (Dictionary<string, object>)data["company"];
      var employees = (List<object>)company["employees"];
      // Alice Johnsonのskillに"Hardware Develop"を追加
      var alice = employees.FirstOrDefault(e => ((Dictionary<string, object>)e)["name"].ToString() == "Alice Johnson") as Dictionary<string, object>;
      if (alice != null)
      {
          var skills = (List<object>)alice["skills"];
          skills.Add("Hardware Develop");
      }
      // Bob Williamsのpositionを"COO"に変更
      var bob = employees.FirstOrDefault(e => ((Dictionary<string, object>)e)["name"].ToString() == "Bob Williams") as Dictionary<string, object>;
      if (bob != null)
      {
          bob["position"] = "COO";
      }
      // 新しい従業員"Taro Yamada"を追加
      var taro = new Dictionary<string, object>
      {
          ["name"] = "Taro Yamada",
          ["position"] = "CTO",
          ["skills"] = new List<string> { "monitoring", "programming" }
      };
      employees.Add(taro);
    }
    // YAMLファイルを非同期で書き込む
    static async Task WriteYamlFileAsync(string filePath, Dictionary<string, object> data)
    {
      var serializer = new SerializerBuilder()
                            .WithNamingConvention(CamelCaseNamingConvention.Instance)
                            .Build();
      var yaml = serializer.Serialize(data);
      await File.WriteAllTextAsync(filePath, yaml);
    }
}
</syntaxhighlight>
<br>
<syntaxhighlight lang="yaml">
# 変更後のYAMLファイル
company:
  name: Tech Solutions Inc.
  founded: 2010
  employees:
    - name: Alice Johnson
      position: CEO
      skills:
        - leadership
        - strategic planning
        - Hardware Develop
    - name: Bob Williams
      position: COO
      skills:
        - programming
        - system architecture
    - name: Taro Yamada
      position: CTO
      skills:
        - monitoring
        - programming
  offices:
    headquarters:
      address: 123 Main St, Techville
      phone: 555-1234
    branch:
      address: 456 Innovation Ave, Codetown
      phone: 555-5678
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br><br>