반응형
반응형

안녕하세요. 오늘은 C# XmlSerializer 사용법에 대해서 알아보겠습니다.

XmlSeralizer Class는 xml 정보를 Deserialize하여 지정된 Class에 정보를 복사하는 Class입니다.



XmlSerializer Class MSDN입니다.


XmlSerializer 생성자 입니다.




메서드입니다.




이벤트입니다.




XmlSerializer을 사용하기 위해서는 먼저 Xml생성해야 합니다.

Serializable되어야 하므로 사용 Class와 동일한 구조로 작성해 줍니다.

 

1
2
3
4
5
6
7
8
9
<?xml version="1.0"?>
  <Item>
    <Item1>Item1 A</Item1>
    <Item2>Item1 B</Item2>
    <Item3>Item1 C</Item3>
    <Page>1</Page>
  </Item>
</Config>
cs

xml에 보이는 Config가 기본 Class 이름입니다.

하위 로드는 Item, Item1, Item2, Item3, Page입니다.

Class구성시 같은 구조로 되어 있어야 정상 동작합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Serializable]
public class Config : XmlPersistableObject
{
      public Config() { Item = new ItemObject(); }
      public ItemObject Item;
}
 
public class ItemObject
{
      public string Item1 { get; set; }
      public string Item2 { get; set; }
      public string Item3 { get; set; }
      public int Page { get; set; }
}
cs

XmlPeristableObject Class를 상속 받아서 Xml 직접 제어하는 Class입니다.

Xml과 동일한 구조입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class XmlPersistableObject
{
      public static T Load<T>(string szFileName) where T : XmlPersistableObject, new()
      {
          T result = default(T);
          using (FileStream stream = File.OpenRead(szFileName))
          {
              result = new XmlSerializer(typeof(T)).Deserialize(stream) as T;
          }
          return result;
      }
 
      public void Save<T>(string szFileName) where T : XmlPersistableObject
      {
          using (FileStream stream = new FileStream(szFileName, FileMode.CreateNew))
          {
              new XmlSerializer(typeof(T)).Serialize(stream, this);
          }
      }
}
cs


XmlSerializer 사용 Class입니다.

T를 사용해서 작성한 Class를 Deserialize하거나 Serialize합니다.


1
2
3
4
5
6
7
8
string szXmlPath = Application.StartupPath + "\\configXml.xml";
Config cnf = new Config();
cnf.Item.Item1 = "Item1 A";
cnf.Item.Item2 = "Item1 B";
cnf.Item.Item3 = "Item1 C";
cnf.Item.Page = 1;
cnf.Save<Config>(szXmlPath);
Config loadxml = Config.Load<Config>(szXmlPath);
cs


사용 예제 입니다.


XmlSerializer을 사용하면 손 쉽게 xml을 컨트롤 할 수 있습니다.


이상입니다.






반응형

+ Recent posts