いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Linq入門記-79 (LINQ to XML, ナビゲーション, Parent)

LINQ to XMLでのナビゲーション系のプロパティについて.

過去の内容は以下から見れます。よろしければご参照くださいませ。


今回のParentプロパティ。
XObjectに所属するプロパティです。
XObjectクラスは、XAttributeとXNodeの親となる抽象クラスです。


そのまんまのプロパティですが、親要素が存在しない場合はnullが返ってくることに注意です。


以下、サンプルです。

namespace Gsf.Samples
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Xml.Linq;

  #region LinqSamples-75
  /// <summary>
  /// LINQ to XMLのサンプルです.
  /// </summary>
  /// <remarks>
  /// ナビゲーション(Parentプロパティ)のサンプルです.
  /// </remarks>
  public class LinqSamples75 : IExecutable
  {
    public void Execute()
    {
      //
      // Parent
      //   文字通り、現在の要素の親要素を取得する.
      //   親要素が存在しない場合、nullとなる.
      //
      var root = BuildSampleXml();
      var elem = root.Elements("Child").First();

      Console.WriteLine("root.Parent = {0}", root.Parent == null ? "null" : root.Parent.ToString());
      Console.WriteLine("elem.Parent = {0}", elem.Parent);

      var newElem = new XElement("GrandChild", "value5");
      Console.WriteLine("newElem.Parent = {0}", newElem.Parent == null ? "null" : newElem.Parent.ToString());

      root.Elements("Child").Last().Add(newElem);
      Console.WriteLine("newElem.Parent = {0}", newElem.Parent);
    }

    XElement BuildSampleXml()
    {
      var root = new XElement("Root",
        new XElement("Child", "value1"),
        new XElement("Child", "value2"),
        new XElement("Child", "value3"),
        new XElement("Child", "value4")
      );

      return root;
    }
  }
  #endregion
}


実行すると以下のようになります。

  root.Parent = null
  elem.Parent = 
    value1
    value2
    value3
    value4
  
  newElem.Parent = null
  newElem.Parent = value4value5


以下、参考リソースです.

================================
過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。