C#でXMLを簡易的に扱うテスト。

環境

OS:Windows7 Pro
VisualStudio:2013 Professional
.NET Framework:4.6.1

コード

using System;
using System.Text;              // UTF8Encodingクラスを使うのに必要。
using System.IO;                // ファイルの読み書きをするのに必要。
using System.Xml.Linq;          // XDocument等を使うのに必要。
using System.Windows.Forms;     // MessageBoxで必要。

/***************************************************************
 * 参照設定に、
 * System
 * System.Windows.Forms     :MessageBoxで必要。
 * System.Xml               :XDocument等で必要。
 * System.Xml.Linq          :XDocument等で必要。
 * を追加する。
 * 
 * プロジェクトのプロパティで、
 * 「出力の種類」を「コンソールアプリケーション」から
 * 「Windowsアプリケーション」へ変更。
 * 
 * 実行ファイルがあるフォルダに、temp.xmlができる。
 * 
 **************************************************************/
public class TestXML
{
    public static void Main()
    {
        // XMLファイルを作成。
        // XMLを設定。
        XDocument xml = new XDocument();
        // XMLの1行目の宣言部分を設定。standalone=yesに設定している。
        XDeclaration xmlDeclaration = new XDeclaration("1.0", "utf-8", "yes");
        xml.Declaration = xmlDeclaration;
        XElement xeName = new XElement("Name", "田中太郎");
        XElement xeTool = new XElement("Tool");
        xeTool.Add(new XElement("First", "かばん"));
        xeTool.Add(new XElement("Second", "はさみ"));
        XElement xePerson = new XElement("Person", xeName, xeTool);
        // XMLにノードを追加。
        xml.Add(xePerson);
        // 書き込むファイルを開く。
        StreamWriter sw = new StreamWriter(@"./temp.xml", false, new UTF8Encoding(true));
        // 書き込む。
        xml.Save(sw);
        // ファイルを閉じる。
        sw.Close();
        MessageBox.Show("XML書き込み完了!");

        // XMLファイルを読み込む。
        // 読み込むファイルを開く。
        StreamReader sr = new StreamReader(@"./temp.xml", new UTF8Encoding(true));
        // ルートノード(Person)にある要素を全て読み込む。
        XElement xElm = XElement.Load(sr);
        // 読み込むファイルを閉じる。
        sr.Close();
        // 読み込んだものを表示。
        MessageBox.Show("名前:" + xElm.Element("Name").Value);
        MessageBox.Show("Tool First:" + xElm.Element("Tool").Element("First").Value);
        MessageBox.Show("Tool Second:" + xElm.Element("Tool").Element("Second").Value);
    }
}

コメント

タイトルとURLをコピーしました