1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#.NETでxmlファイル読込

Posted at

やり方(サンプルexe作成)

プロジェクト作成

VisualStudioでプロジェクト作成。

image.png

xmlファイル作成

プロジェクト上で右クリック ⇒ 追加 ⇒ 新しい項目 。
image.png

今回は『setting.xml』って名前でxml作成。
image.png

setting.xmlの中身はこうしてみた
<?xml version="1.0" encoding="utf-8" ?>
<root>
	
	<うにゃあ>うにゃあの中身だよ。</うにゃあ>
	
	<task>
		<name>task_1_name</name>
		<message>task_1_message</message>
	</task>
	
	<task>
		<name>task_2_name</name>
		<message>task_2_message</message>
	</task>
	
	<task>
		<name>task_3_name</name>
		<message>task_3_message</message>
	</task>
	
</root>

デバッグ時に『ファイル存在しません例外』にならないように、下記のように設定しておく。
image.png

ソースコード

using System;
using System.Xml.Linq;

namespace XmlLoad
{
    internal class Program
    {
        static void Main(string[] args)
        {

            //サンプルだからtry catch無し。

            //exeと同じフォルダーにある『setting.xml』ってファイルを対象にするよ。
            string xml_file_path_ = System.AppDomain.CurrentDomain.BaseDirectory + "setting.xml";

            //xmlを読み込め。
            XDocument xml_ = XDocument.Load(xml_file_path_);

            //ルートタグを変数に。
            XElement root_element_ = xml_.Element("root");

            //ルートタグ直下にあるタグの値。
            //日本語のタグも扱えるかどうかの確認。
            Console.WriteLine(root_element_.Element("うにゃあ").Value);

            //ルートタグ直下にあるtaskっていう名前のタグ一覧を走査。
            foreach (XElement task_element_ in root_element_.Elements("task"))
            {
                Console.WriteLine(task_element_.Element("name").Value);
                Console.WriteLine(task_element_.Element("message").Value);
            }

            //確認用にコンソール閉じずに残す。
            Console.ReadLine();

        }
    }
}

F5でデバッグ実行した結果

image.png

蛇足

そんなに難しくはない。

バージョン

Windows 10 Pro 21H2 OSビルド 19045.2311
Microsoft Visual Studio Community 2022 (64 ビット) - Current Version 17.3.6
Microsoft .NET Framework Version 4.8.04084

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?