C#とXmlDocumentによるXMLドキュメントの読み書き操作

XMLとは

XML(Extensible Markup Language)は、オープンなテキスト形式として広く利用されています。詳細についてはW3Cの公式サイトをご確認ください:XML仕様

.NETにおけるXML処理手法

  • XmlDocumentを用いたXMLドキュメントの操作
  • XmlReaderおよびXmlWriterによるストリーム処理
  • LINQ to XMLによるデータ操作
  • XmlSchemaによる構造定義
  • クラスのXMLシリアライズ・デシリアライズ
  • XPathによるノード検索
  • XSLTによる変換処理

XmlDocumentによるXML操作

以下のXMLサンプルを例に説明します:

<?xml version="1.0" encoding="utf-8" ?>
<students>
  <!--コメント内容-->
  <student name="田中太郎">
    <courses>
      <course name="国語">
        <teacherComment>
          <![CDATA[
        国語担当からのコメント
        ]]>
        </teacherComment>      
    </course>

      <course name="算数">
        <teacherComment>
          <![CDATA[
        算数担当からのコメント
        ]]>
        </teacherComment>
      </course>
    </courses>
  </student>
</students>

XMLの読み込み処理

すべての学生情報を走査し、各属性と子要素の値を出力するコード例:

using System;
using System.Xml;

class XmlReaderDemo
{
    static void ProcessXmlFile()
    {
        string filePath = @"sample.xml";
        XmlDocument document = new XmlDocument();
        document.Load(filePath);

        XmlNodeList students = document.SelectNodes("//student");
        
        foreach (XmlNode student in students)
        {
            string studentName = student.Attributes["name"]?.Value ?? "";
            Console.WriteLine($"生徒名: {studentName}");

            XmlNode coursesContainer = student.SelectSingleNode("courses");
            XmlNodeList courseItems = coursesContainer?.ChildNodes;

            if (courseItems != null)
            {
                foreach (XmlNode course in courseItems)
                {
                    string subject = course.Attributes["name"]?.Value ?? "";
                    Console.Write($"\t{subject} - ");
                    
                    XmlNode commentWrapper = course.FirstChild;
                    if (commentWrapper?.FirstChild is XmlCDataSection commentData)
                    {
                        Console.WriteLine(commentData.Value?.Trim());
                    }
                }
            }
        }
    }
}

XmlDocumentはXmlNodeを継承しており、FirstChild、LastChild、NextSibling、PreviousSiblingプロパティで個別ノードを取得できます。またChildNodesプロパティで全子ノードを取得可能です。XPath式を使用してSelectNodes()またはSelectSingleNode()メソッドで条件に合致するノードを選択することもできます。

XMLの書き込み処理

同じ構造を持つXMLをプログラムで生成する例:

using System;
using System.Xml;

class XmlWriterDemo
{
    static void GenerateXmlDocument()
    {
        XmlDocument outputDoc = new XmlDocument();
        
        // XML宣言の作成
        XmlDeclaration declaration = outputDoc.CreateXmlDeclaration("1.0", "utf-8", null);
        outputDoc.AppendChild(declaration);

        // ルート要素の作成
        XmlElement rootElement = outputDoc.CreateElement("students");
        
        // 学生要素の作成
        XmlElement studentElement = outputDoc.CreateElement("student");
        studentElement.SetAttribute("name", "山田花子");

        // 科目情報の構築
        XmlElement subjectsContainer = outputDoc.CreateElement("courses");
        
        XmlElement subjectElement = outputDoc.CreateElement("course");
        subjectElement.SetAttribute("name", "英語");
        
        XmlElement feedbackElement = outputDoc.CreateElement("teacherComment");
        XmlCDataSection feedbackContent = outputDoc.CreateCDataSection("英語教師からの評価");
        feedbackElement.AppendChild(feedbackContent);
        
        subjectElement.AppendChild(feedbackElement);
        subjectsContainer.AppendChild(subjectElement);
        studentElement.AppendChild(subjectsContainer);
        rootElement.AppendChild(studentElement);
        outputDoc.AppendChild(rootElement);

        // ファイルへの保存
        outputDoc.Save("output.xml");
        Console.WriteLine("XMLファイルが正常に生成されました");
    }
}

XmlDocumentを使用したXML生成では、CreateElementメソッドで要素を作成し、CreateAttributeで属性を定義します。AppendChildメソッドで要素を追加し、属性はAttributesコレクションにAppendメソッドで追加します。

タグ: C# XmlDocument XML .NET Framework

8月14日 22:18 投稿