4
5

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-02-04

C# リクエストしたXMLデータをクラスに取り込みたい

作ろうと思った理由

 APIからXMLを取得した際に、オブジェクトを指定して値を手軽に取りたかったから

イメージ図

URLRequest.png

XMLファイルとデータクラス

簡単なサンプル用のxmlを作成する。

sample.xml
<?xml version="1.0" encoding="UTF-8"?>
<Root>
  <data>
    <id>01</id>
    <text>Hello!</text>
  </data>
</Root>

XMLの構造にあわせてデータクラスを作成する。
※このときクラスやメンバーをPublicにする必要がある。Seriallizerで読み込めないときは、Publicではないことを疑った方がいい

SampleXMLData.cs
using System.Xml.Serialization;

namespace URLRequest
{
    [XmlRoot("Root")]
    public class SampleXMLData
    {
        [XmlElement("data")]
        public XMLData xmlData;
    }

    public class XMLData
    {
        [XmlElement("id")]
        public string id;

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

Seriallizer

XMLの文字列をデータクラスに流し込む

CustomXMLSeriallizer.cs
using System.IO;
using System.Xml.Serialization;

namespace URLRequest
{
    public static class CustomXMLSeriallizer
    {
        public static T LoadXmlDataString<T>(string xmltext) where T : class
        {
            XmlSerializer serializer =new XmlSerializer(typeof(T));
            StringReader reader = new StringReader(xmltext);
            T loadAry = (T)serializer.Deserialize(reader);
            reader.Close();
            return loadAry;
        }
    }
}

メイン

Program.cs
using System;
using System.IO;
using System.Net;
using System.Text;

namespace URLRequest
{
    class Program
    {
        static void Main(string[] args)
        {
            Encoding enc = Encoding.GetEncoding("UTF-8");
            string url = "http://127.0.0.1/sandbox/sample/xml/sample.xml";

            WebRequest req = WebRequest.Create(url);
            WebResponse res = req.GetResponse();

            Stream st = res.GetResponseStream();
            StreamReader sr = new StreamReader(st, enc);
            string xml = sr.ReadToEnd();
            sr.Close();
            st.Close();

            Console.WriteLine(xml);

            SampleXMLData xmlDatas = CustomXMLSeriallizer.LoadXmlDataString<SampleXMLData>(xml);

            Console.WriteLine("--------");
            Console.WriteLine("id  :" + xmlDatas.xmlData.id);
            Console.WriteLine("text:" + xmlDatas.xmlData.text);
            Console.WriteLine("--------");
            Console.ReadKey();
        }
    }
}

結果

ResultConsole.png

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?