posted by 방랑군 2009. 9. 24. 11:27

첨부파일 :

XMLFile2.xml

<?xml version="1.0" encoding="UTF-8" ?>

<Root>

  <Record>

    <Field1>Field1_0</Field1>

    <Field2>Field2_0</Field2>

  </Record>

  <Record2 Field2="Field2_0" Field3="Field3_1" />

  <Field1>Field1_0</Field1>

  <Field2>Field2_0</Field2>

</Root>




>xsd.exe XMLFile2.xml
XMLFile2.xml

<?xml version="1.0" encoding="utf-8"?>

<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

  <xs:element name="Root">

    <xs:complexType>

      <xs:sequence>

        <xs:element name="Field1" type="xs:string" minOccurs="0" />

        <xs:element name="Field2" type="xs:string" minOccurs="0" />

        <xs:element name="Record" minOccurs="0" maxOccurs="unbounded">

          <xs:complexType>

            <xs:sequence>

              <xs:element name="Field1" type="xs:string" minOccurs="0" />

              <xs:element name="Field2" type="xs:string" minOccurs="0" />

            </xs:sequence>

          </xs:complexType>

        </xs:element>

        <xs:element name="Record2" minOccurs="0" maxOccurs="unbounded">

          <xs:complexType>

            <xs:attribute name="Field2" type="xs:string" />

            <xs:attribute name="Field3" type="xs:string" />

          </xs:complexType>

        </xs:element>

      </xs:sequence>

    </xs:complexType>

  </xs:element>

  <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">

    <xs:complexType>

      <xs:choice minOccurs="0" maxOccurs="unbounded">

        <xs:element ref="Root" />

      </xs:choice>

    </xs:complexType>

  </xs:element>

</xs:schema>


>xsd.exe XMLFile2.xsd /c
XMLFile2.cs

//------------------------------------------------------------------------------

// <auto-generated>

//     This code was generated by a tool.

//     Runtime Version:2.0.50727.3082

//

//     Changes to this file may cause incorrect behavior and will be lost if

//     the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------


using System.Xml.Serialization;


// 

// This source code was auto-generated by xsd, Version=2.0.50727.1432.

// 



/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]

public partial class Root {

    

    private string field1Field;

    

    private string field2Field;

    

    private RootRecord[] recordField;

    

    private RootRecord2[] record2Field;

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public string Field1 {

        get {

            return this.field1Field;

        }

        set {

            this.field1Field = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public string Field2 {

        get {

            return this.field2Field;

        }

        set {

            this.field2Field = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("Record", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public RootRecord[] Record {

        get {

            return this.recordField;

        }

        set {

            this.recordField = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("Record2", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public RootRecord2[] Record2 {

        get {

            return this.record2Field;

        }

        set {

            this.record2Field = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]

public partial class RootRecord {

    

    private string field1Field;

    

    private string field2Field;

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public string Field1 {

        get {

            return this.field1Field;

        }

        set {

            this.field1Field = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public string Field2 {

        get {

            return this.field2Field;

        }

        set {

            this.field2Field = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]

public partial class RootRecord2 {

    

    private string field2Field;

    

    private string field3Field;

    

    /// <remarks/>

    [System.Xml.Serialization.XmlAttributeAttribute()]

    public string Field2 {

        get {

            return this.field2Field;

        }

        set {

            this.field2Field = value;

        }

    }

    

    /// <remarks/>

    [System.Xml.Serialization.XmlAttributeAttribute()]

    public string Field3 {

        get {

            return this.field3Field;

        }

        set {

            this.field3Field = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]

public partial class NewDataSet {

    

    private Root[] itemsField;

    

    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("Root")]

    public Root[] Items {

        get {

            return this.itemsField;

        }

        set {

            this.itemsField = value;

        }

    }

}




쓸데없는 Attribute 제거 후 객체 모양

using System.IO;

using System.Xml;

using System.Xml.Serialization;


using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace Console_XML.In4

{


    /// <remarks/>

    [System.Serializable]

    //[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

    public class Root

    { 


        /// <remarks/>

        

        public RootRecord Record

        {

            get { return _Record; }

            set { _Record = value; }

        }

        private RootRecord _Record = new RootRecord();



        /// <remarks/>

        

        public RootRecord2 Record2

        {

            get { return _Record2; }

            set { _Record2 = value; }

        }

        private RootRecord2 _Record2 = new RootRecord2();



        /// <remarks/>

        

        public string Field1

        {

            get { return _Field1; }

            set { _Field1 = value; }

        }

        private string _Field1 = "";



        /// <remarks/>

        

        public string Field2

        {

            get { return _Field2; }

            set { _Field2 = value; }

        }

        private string _Field2 = "";


    }


    /// <remarks/>

    [System.Serializable]    

    public class RootRecord

    {


        /// <remarks/>

        

        public string Field1

        {

            get { return _Field1; }

            set { _Field1 = value; }

        }

        private string _Field1 = "";



        /// <remarks/>

        

        public string Field2

        {

            get { return _Field2; }

            set { _Field2 = value; }

        }

        private string _Field2 = "";


    }


    /// <remarks/>

    [System.Serializable]    

    public class RootRecord2

    {


        /// <remarks/>

        [System.Xml.Serialization.XmlAttributeAttribute()]

        public string Field2

        {

            get { return _Field2; }

            set { _Field2 = value; }

        }

        private string _Field2 = "";



        /// <remarks/>

        [System.Xml.Serialization.XmlAttributeAttribute()]

        public string Field3

        {

            get { return _Field3; }

            set { _Field3 = value; }

        }

        private string _Field3 = "";


    }


}



XML <-> CLASS 할 함수

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



using System.Xml;

using System.IO;

using System.Xml.Serialization;



namespace Console_XML

{

    class xxml

    {


        /// <summary>

        /// XML -> yyyyMMdd\FILE

        /// </summary>

        /// <param name="doc"></param>

        /// <param name="path"></param>

        public static void XMLDoctoFile(XmlDocument doc, string path)

        {

            string _Date = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string[] _path = path.Split(new char[] { '\\' });

            string _fullpath = "";

            for (int i = 0; i < _path.Length - 1; i++)

            {

                _fullpath += _path[i] + "\\";


            }

            // 디렉토리 검색

            if (!System.IO.Directory.Exists(_fullpath + "\\" + _Date))

            {

                Directory.CreateDirectory(_fullpath + "\\" + _Date);

            }


            path = _fullpath + "\\" + _Date + "\\" + _path[_path.Length - 1];


            XmlTextWriter writer = new XmlTextWriter(path, new UTF8Encoding());

            try

            {

                writer.Formatting = Formatting.Indented;

                writer.Indentation = 4;

                doc.WriteContentTo(writer);

            }

            finally

            {

                writer.Close();

            }

        }



        /// <summary>

        /// XML -> yyyyMMdd\FILE

        /// </summary>

        /// <param name="doc"></param>

        /// <param name="path"></param>

        public static void XMLDoctoFileEx(XmlDocument doc, string path)

        {

            string _Date = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string _Hour = DateTime.Now.ToString("HH", System.Globalization.DateTimeFormatInfo.InvariantInfo);

            string[] _path = path.Split(new char[] { '\\' });

            string _dirPath = "";

            string _fullpath = "";

            for (int i = 0; i < _path.Length - 1; i++)

            {

                _fullpath += _path[i] + "\\";


            }


            _dirPath = _fullpath + "\\" + _Date + "\\" + _Hour;

            // 디렉토리 검색

            if (!System.IO.Directory.Exists(_dirPath))

            {

                Directory.CreateDirectory(_dirPath);

            }


            path = _dirPath + "\\" + _path[_path.Length - 1];


            XmlTextWriter writer = new XmlTextWriter(path, new UTF8Encoding());

            try

            {

                writer.Formatting = Formatting.Indented;

                writer.Indentation = 4;

                doc.WriteContentTo(writer);

            }

            catch (Exception err)

            {

                System.Diagnostics.EventLog.WriteEntry("VTFramework", "[vS_XML:XMLDoctoFileEx]:" + err.Message, System.Diagnostics.EventLogEntryType.Error);

            }

            finally

            {

                writer.Close();

            }

        }


        /// <summary>

        /// 객체를 xmlDocument로 전환 하는 함수.

        /// </summary>

        /// <param name="obj"></param>

        /// <returns></returns>

        public static XmlDocument ToMessage(object obj)

        {

            try

            {

                XmlSerializer serializer = new XmlSerializer(obj.GetType());

                MemoryStream stream = new MemoryStream();

                StreamReader reader = new StreamReader(stream);

                serializer.Serialize(stream, obj);

                stream.Position = 0;

                XmlDocument doc = new XmlDocument();

                doc.LoadXml(reader.ReadToEnd());

                try

                {

                    return doc;

                }

                finally

                {

                    reader.Close();

                    stream.Close();

                }

            }

            catch (Exception exc)

            {

                System.Diagnostics.EventLog.WriteEntry("VTFramework", "[vS_XML:ToMessage]:" + exc.Message, System.Diagnostics.EventLogEntryType.Error);

                throw new Exception("객체 생성중 오류가 발생했읍니다![ToInstance", exc);

            }

        }


        /// <summary>

        /// xmlDocument를 객체로 변환하는 함수

        ///  XML -> CLASS

        /// ex)

        ///   1. 변환할 클래스의 필드가 적어도 많아도 적용이 됨

        ///   2. 다른 필드가 존재해도 적용이 됨

        /// </summary>

        /// <param name="doc"></param>

        /// <param name="type"></param>

        /// <returns></returns>

        public static object ToInstance(XmlDocument doc, System.Type type)

        {

            try

            {

                XmlSerializer serializer = new XmlSerializer(type);

                MemoryStream writeStream = new MemoryStream();

                MemoryStream readStream = new MemoryStream();


                XmlTextWriter writer = new XmlTextWriter(writeStream, null);

                doc.WriteContentTo(writer);

                writer.Flush();


                writeStream.Position = 0;


                writeStream.WriteTo(readStream);

                writer.Close();

                writeStream.Close();


                readStream.Position = 0;

                XmlTextReader reader = new XmlTextReader(readStream);

                try

                {

                    return serializer.Deserialize(reader);

                }

                finally

                {

                    reader.Close();

                    readStream.Close();

                }

            }

            catch (Exception exc)

            {

                throw new Exception("객체 생성중 오류가 발생했읍니다![ToInstance", exc);

            }

        }

    }

}




XML -> CLASS 객체로 변환 소스

doc.Load(@"XMLFile2.xml");


Console_XML.In4.Root objInstance3 = (Console_XML.In4.Root)xxml.ToInstance(doc, typeof(Console_XML.In4.Root));