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

 
(同じ利用者による、間の3版が非表示)
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>
207行目: 210行目:
<br>
<br>
==== YAMLファイルの読み込み ====
==== YAMLファイルの読み込み ====
以下の例では、YamlDotNetライブラリを使用して、YAMLファイルを読み込んでいる。<br>
以下の例では、YamlDotNetライブラリを使用して、指定されたYAMLファイルを非同期で読み込み・解析している。<br>
<br>
* StreamReaderクラスを使用してファイルを開く。
* YamlStreamクラスのLoadAsyncメソッドを使用して、ファイルを非同期で読み込む。
* 解析したYAMLデータのルートノードを返す。
* ReadYamlFileAsyncメソッドは、ファイルを非同期で読み込み、YAMLデータを解析する。
* ProcessYamlDataAsyncメソッドは、解析したYAMLデータを処理する。
*: 会社名、設立年、従業員情報、オフィス情報を順に取得する。
*: 各セクションでYAMLノードを適切な型 (YamlMappingNode、YamlSequenceNode) にキャストして処理する。
<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.Threading.Tasks;
using YamlDotNet.RepresentationModel;
class Program
{
    static async Task Main(string[] args)
    {
      string filePath = "sample.yaml";  // YAMLファイルのパス
      try
      {
          // YAMLファイルを非同期で読み込み、YAMLデータを解析
          var yaml = await ReadYamlFileAsync(filePath);
          // 解析したYAMLデータを処理
          await ProcessYamlDataAsync(yaml);
      }
      catch (Exception ex)
      {
          Console.WriteLine($"エラーが発生: {ex.Message}");
      }
    }
    // YAMLファイルを非同期で読み込む
    static async Task<YamlMappingNode> ReadYamlFileAsync(string filePath)
    {
      using (var streamReader = new StreamReader(filePath))
      {
          // YAMLストリームを作成
          var yaml = new YamlStream();
           
          // ファイルを非同期で読み込み、YAMLデータを解析
          await yaml.LoadAsync(streamReader);
          // ルートノードを取得して、YamlMappingNodeにキャスト
          return (YamlMappingNode)yaml.Documents[0].RootNode;
      }
    }
    // 解析したYAMLデータを処理
    static async Task ProcessYamlDataAsync(YamlMappingNode root)
    {
      // 会社情報を取得
      var company = (YamlMappingNode)root["company"];
      // 会社名と設立年を出力
      Console.WriteLine($"会社名: {company["name"]}");
      Console.WriteLine($"設立年: {company["employees"]}");
      // 従業員情報を取得
      var employees = (YamlSequenceNode)company["employees"];
      Console.WriteLine("従業員一覧:");
      foreach (var employee in employees.Children)
      {
          var employeeNode = (YamlMappingNode)employee;
          Console.WriteLine($"名前: {employeeNode["name"]}");
          Console.WriteLine($"役職: {employeeNode["position"]}");
          var skills = (YamlSequenceNode)employeeNode["skills"];
          Console.WriteLine("スキル:");
          foreach (var skill in skills)
          {
            Console.WriteLine($"- {skill}");
          }
      }
      // オフィス情報を取得
      var offices = (YamlMappingNode)company["offices"];
      Console.WriteLine("オフィス情報:");
      foreach (var office in offices.Children)
      {
          Console.WriteLine($"{office.Key}:");
          var officeNode = (YamlMappingNode)office.Value;
          Console.WriteLine($"住所: {officeNode["address"]}");
          Console.WriteLine($"電話: {officeNode["phone"]}");
      }
      // 非同期処理をシミュレートするために1秒待機
      await Task.Delay(1000);
    }
}
</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#">
  <syntaxhighlight lang="c#">
  var deserializer = new DeserializerBuilder().Build();
  using System;
  var yaml         = File.ReadAllText("config.yaml");
using System.IO;
  var result      = deserializer.Deserialize<Dictionary<string, object>>(yaml);
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>