프로그래밍/C#

[C#] XML Serialization, Deserialize

큐레이트 2020. 12. 7. 10:55
반응형

clientConfig.xml

<?xml version="1.0" encoding="utf-8" ?>
<config>
	<server>
		<ip>127.0.0.1</ip>
		<port>8080</port>
	</server>

	<application width="100" height="100" />
</config>

Xml 파일 읽어서 사용할 객체

[XmlRoot("config")]
public class ClientConfigModel
{
    [XmlElement("server")]
    public ConfigServer server { get; set; }

    [XmlElement("application")]
    public ConfigApplication application { get; set; }
}

[Serializable()]
public class ConfigServer
{
    [XmlElement("ip")]
    public string ip { get; set; }

    [XmlElement("port")]
    public int port { get; set; }
}

[Serializable()]
public class ConfigApplication
{
    [XmlAttribute("width")]
    public int width { get; set; }

    [XmlAttribute("height")]
    public int height { get; set; }
}

 

데이터 읽어오기

/// <summary>
/// 설정파일 읽어오기
/// </summary>
/// <param name="path">설정파일경로</param>
public static void Read(string path)
{
    if (System.IO.File.Exists(path))
    {
        using (var sr = new StreamReader(path))
        {
            var xs = new XmlSerializer(typeof(Model.ClientConfigModel));
            var configModel = (Model.ClientConfigModel)xs.Deserialize(sr);

            Console.WriteLine("ip : {0}", configModel.server.ip);
            Console.WriteLine("port : {0}", configModel.server.port);

            Console.WriteLine("width : {0}", configModel.application.width);
            Console.WriteLine("height : {0}", configModel.application.height);

        }
    }
}

 

Console 결과

 

반응형