출처 : 본인



2015/04/01 - [프로그램 자료/Visual C#] - Class를 Xml 파일로 바꾸기








파일 저장은 잘 되었는데, 객체로 변환이 안되길래 찾아보니 xml 파일을 저장할 때 UTF-8 BOM 방식으로 저장을 하고 있었다.

그래서 저장할 때 BOM을 제거한 뒤 저장하고 다시 읽어오니 잘 되더라.





샘플로 작성한 Settings 클래스 - 파일이 없을 때는 bool 변수를 받는 생성자로 생성하면 기본값을 줄 수 있음

[XmlRoot("Settings", Namespace = "http://www.motolies.com")]

public class Settings

{

    [XmlIgnore]

    public static string path = Environment.CurrentDirectory + "//settings.xml";

 

    [XmlArray("WithoutExtensionList"), XmlArrayItem(typeof(String), ElementName = "WithoutExtension")]

    public List<string> woExtensionList = new List<string>();

 

    [XmlArray("FilterExtensionList"), XmlArrayItem(typeof(String), ElementName = "FilterExtension")]

    public List<string> schExtensionList = new List<string>();

 

    [XmlElement("Notepad_PP_Path")]

    public string NotepadPlusPath { get; set; }

 

    public Settings() { }

    public Settings(bool isNew)

    {

        woExtensionList = new List<string>

        {

            ".dll", ".exe", ".db", ".svn-base", ".pdb"

        };

 

        schExtensionList = new List<string>

        {

            "*.*"

            ,"*.txt"

            ,"*.c;*.cpp;*.h;*.cs;*.sql;*.html;*.aspx;*.css;*.js;*.py;*.xml"

        };

    }

}




사용법

static Settings set = new Settings();

if (File.Exists(Settings.path))

{

    //셋팅파일 읽기

    set = XMLSerializer.FromXMLFile<Settings>(Settings.path);

}

else

{

    //만들기

    set.ExtensionList = removeFiler;

    XMLSerializer.ToXMLFile<Settings>(set, Settings.path);

}





직렬화 관련 클래스

public static class XMLSerializer

{

    static Encoding utf8WithoutBom = new UTF8Encoding(false);

 

    public static T FromXML<T>(string xml)

    {

        using (StringReader sr = new StringReader(xml))

        {

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

            return (T)serializer.Deserialize(sr);

        }

    }

    public static T FromXMLFile<T>(string path)

    {

        string xml = string.Empty;

        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))

        {

            using (StreamReader sr = new StreamReader(fs, utf8WithoutBom, true))

            {

                sr.BaseStream.Seek(0, SeekOrigin.Begin);

                while (sr.Peek() > -1)

                {

                    xml = sr.ReadToEnd();

                }

            }

        }

        using (StringReader sr = new StringReader(xml))

        {

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

            return (T)serializer.Deserialize(sr);

        }

 

    }

    public static string ToXML<T>(T obj, string rootName = null)

    {

        using (MemoryStream stream = new MemoryStream())

        using (StreamWriter sw = new StreamWriter(stream, utf8WithoutBom))

        {

            XmlSerializer xmlSerializer;

            if (string.IsNullOrEmpty(rootName))

            {

                xmlSerializer = new XmlSerializer(typeof(T));

            }

            else

            {

                xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));

            }

            xmlSerializer.Serialize(sw, obj);

 

            return Encoding.UTF8.GetString(stream.ToArray());

        }

    }

    public static void ToXMLFile<T>(T obj, string path, string rootName = null)

    {

 

        using (MemoryStream stream = new MemoryStream())

        using (StreamWriter sw = new StreamWriter(stream, utf8WithoutBom))

        {

            XmlSerializer xmlSerializer;

            if (string.IsNullOrEmpty(rootName))

            {

                xmlSerializer = new XmlSerializer(typeof(T));

            }

            else

            {

                xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));

            }

            xmlSerializer.Serialize(sw, obj);

 

            string strXML = Encoding.UTF8.GetString(stream.ToArray());

            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))

            {

                using (StreamWriter swrw = new StreamWriter(fs, utf8WithoutBom))

                {

                    swrw.WriteLine(strXML);

                }

            }

        }

    }

}











Posted by motolies
,