본문 바로가기
C#(CSharp)/Etc

XSD -> Class 사용하기

by swconsulting 2015. 3. 17.

두개 파일을 첨부합니다. 1개는 XSD이고, 다른 하나는 XSD를 class로 변환한 CS 파일입니다. 



XSD_XML_CS.zip



[USE CS]

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

using System.Xml.Serialization;

using System.IO;

 

namespace XmlLib

{

    public class XmlUtil

    {

        private string curPath = @"stickyNoteConfig.xml";

 

        public object GetObjFromXml(string fileName)

        {

            XmlSerializer serializer = new XmlSerializer(typeof(StickyNoteConfigInfo));

            StickyNoteConfigInfo xmlToObj = new StickyNoteConfigInfo();

 

            using(StreamReader reader = new StreamReader(curPath))

            {

                xmlToObj = (StickyNoteConfigInfo)serializer.Deserialize(reader);

                reader.Dispose();

                reader.Close();

            }

 

            return xmlToObj;   

        }

 

        public void SetObjToXml(string fileName, object xmlObj)

        {

            XmlSerializer serializer = new XmlSerializer(typeof(StickyNoteConfigInfo));

            StickyNoteConfigInfo objToXml = xmlObj as StickyNoteConfigInfo;

 

            using (StreamWriter writer = new StreamWriter(curPath))

            {

                serializer.Serialize(writer, objToXml);

                writer.Close();

            }

 

        }

    }

 

}


[UnitTest]

using System;

using Microsoft.VisualStudio.TestTools.UnitTesting;

 

using XmlLib;

 

namespace FrameworkUnitTestProject

{

    [TestClass]

    public class XmlUnitTest



    {

        [TestMethod]

        public void DeserializeTestMethod()

        {

            XmlUtil xmlUtil = new XmlUtil();

 

            object xmlObj = xmlUtil.GetObjFromXml("stickyNoteConfig.xml");

 

            StickyNoteConfigInfo stickNoteConfig = xmlObj as StickyNoteConfigInfo;           

        }

 

        [TestMethod]

        public void SerializeTestMethod()

        {

            XmlUtil xmlUtil = new XmlUtil();

 

            object xmlObj = xmlUtil.GetObjFromXml("stickyNoteConfig.xml");

 

            StickyNoteConfigInfo stickNoteConfig = xmlObj as StickyNoteConfigInfo;           

 

            stickNoteConfig.buildDate = DateTime.Now;

            stickNoteConfig.config.userName = DateTime.Now.ToString();

 

            xmlUtil.SetObjToXml("", stickNoteConfig);

        }

    }

 

}


출처 : 다년간의 프로그래밍 경험