5
6

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 5 years have passed since last update.

C#で外部から取得したXMLをモデルクラスにマッピングする方法

Last updated at Posted at 2016-05-18

[メモ書き]

たとえば下記のようなXMLが取得できる場合を想定

<report>
  <head>
    <title>Title</title>
    <type>Type</type>
  </head>
  <body>
    <item>
      <name>A</name>
      <age>20</age>
    </item>
    <item>
      <name>B</name>
      <age>22</age>
    </item>
  </body>
</report>

下記クラスを定義する

model.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Test
{
	[XmlRoot("report")]
	public class Report
	{
		[XmlElement("head")]
		public Head head;

		[XmlElement("body")]
		public Body body;
	}

	public class Head
	{
		[XmlElement("title")]
		public string title;

		[XmlElement("type")]
		public string type;
	}

	public class Body
	{
		[XmlElement("item")]
		public List<Item> items;
	}

	public class Item
	{
		[XmlElement("name")]
		public string name;

		[XmlElement("age")]
		public int age;
	}
}
main.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Test
{
	public void main() 
	{
		var url = "{url}";
		HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
		HttpWebResponse response = request.GetResponse() as HttpWebResponse;
		var stream = response.GetResponseStream();
		XmlSerializer serializer = new XmlSerializer(typeof(Report));
		var report = serializer.Deserialize(stream) as Report;
	}
}
5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?