[C#] C# 코드로 XML 문서 생성하는 방법



이번 포스팅에서는 C# 코드로 XML 문서 생성하는 방법에 대해서 알아보도록 하겠습니다.


지금 제가 현재 종사하고 있는 디스플레이 업계쪽에서는 설비에서 검사한 데이터들을 RawData로 남기고 있는데, 해당 RawData를 XML로 생성하고 기록하기도 하고, .CSV 파일로 생성하여 남기기도 합니다.


그렇기 때문에 한번 코드를 작성한다면, 다음에 두고두고 쓰일 XML 문서 만드는 방법에 대해서 알아보도록 하겠습니다.


프로젝트는 빈 윈폼 프로젝트를 생성해 주시고,

아래와 같이 Button 컨트롤 하나를 배치시켜 주시기 바랍니다.


그리고 아래와 같이 School, Student 클래스를 생성해 주시고, 아래와 같이 코드를 작성해 주시기 바랍니다.


Main.cs


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.IO;

using System.Linq;

using System.Reflection;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Xml;

 

namespace XMlTest

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btn_xmlCreate_Click(object sender, EventArgs e)

        {

            try

            {

                School _school = new School();

                _school.SCHOOL_NAME = "학교 이름";

                _school.SCHOOL_ADDRESS = "학교 주소";

                _school.SCHOOL_STUDENT_COUNT = "학생 ";

 

                Student _student = new Student();

                _student.STUDENT_NAME = "학생 이름";

                _student.STUDENT_GRADE = "학생 학년";

 

 

                DataTable table1 = new DataTable("School");

                table1.Columns.Add(_school.SCHOOL_NAME);

                table1.Columns.Add(_school.SCHOOL_ADDRESS);

                table1.Columns.Add(_school.SCHOOL_STUDENT_COUNT);

 

                DataTable table2 = new DataTable("Student");

                table2.Columns.Add(_student.STUDENT_NAME);

                table2.Columns.Add(_student.STUDENT_GRADE);

 

                DataSet ds = new DataSet("Test");

                ds.Tables.Add(table1);

                ds.Tables.Add(table2);

 

                Make_XMLFile(table1, table2);

            }

            catch(Exception ex)

            {

                MessageBox.Show(string.Format("XML 파일 생성 실패 {0}", ex.ToString()));

            }

        }

 

        private string Make_XMLFile(DataTable sch_data, DataTable stu_data)

        {

 

            XmlDocument Doc = Make_XML_FILE(sch_data, stu_data);

      

            int retryCnt = 5;

            string xmlFileName = "School.xml";

            DirectoryInfo DirInfoi = new DirectoryInfo(Environment.CurrentDirectory + "\\test");

 

            while (DirInfoi.Exists == false && retryCnt > 0)

            {

                retryCnt--;

                DirInfoi.Create();

                DirInfoi = new DirectoryInfo(Environment.CurrentDirectory + "\\test");

            }

            if (retryCnt == 0)

                return string.Empty;

            retryCnt = 5;

            DirInfoi = new DirectoryInfo(Environment.CurrentDirectory + "\\test");

            while (DirInfoi.Exists == false && retryCnt > 0)

            {

                DirInfoi.Create();

                DirInfoi = new DirectoryInfo(Environment.CurrentDirectory + "\\test");

            }

            

            Doc.Save(Environment.CurrentDirectory + "\\test" + xmlFileName);

              

            return xmlFileName;

        }

 

        public XmlDocument Make_XML_FILE(DataTable sch_data, DataTable stu_data)

        {

 

            XmlDocument Doc = new XmlDocument();

            XmlElement inventory = Doc.CreateElement("SCHOOL");

            XmlElement SCHOOL_info_data = SCHOOL_Info(Doc, sch_data);

 

            // STU_INFOR

            XmlElement STUDENT_info_data = STUDENT_Info(Doc, stu_data);

 

            //문서 완성

            inventory.AppendChild(SCHOOL_info_data);

            inventory.AppendChild(STUDENT_info_data);

            Doc.AppendChild(inventory);

            //Doc.Save("test.xml");

            return Doc;

        }

 

        public XmlElement SCHOOL_Info(XmlDocument doc, DataTable sch_data)

        {

            XmlElement SCHOOL_INF = doc.CreateElement("School_INF");

 

            List<PropertyInfo> P_List = new List<PropertyInfo>();

            School _school = new School();

            P_List.AddRange(_school.GetType().GetProperties());

 

            

 

            for (int i = 0; i < P_List.Count(); i++)

            {

                XmlElement tmp_Elm = doc.CreateElement(P_List[i].Name);

                string[] columnNames = sch_data.Columns.Cast<DataColumn>()

                                 .Select(x => x.ColumnName)

                                 .ToArray();

                tmp_Elm.InnerText = columnNames[i].ToString();

                SCHOOL_INF.AppendChild(tmp_Elm);

            }

 

            return SCHOOL_INF;

        }

 

        public XmlElement STUDENT_Info(XmlDocument doc, DataTable stu_data)

        {

            XmlElement STUDENT_INF = doc.CreateElement("Student_INF");

 

            Student _student = new Student();

 

            List<PropertyInfo> P_List = new List<PropertyInfo>();

            P_List.AddRange(_student.GetType().GetProperties());

 

            XmlElement student = doc.CreateElement("Student");

            for (int col = 0; col < P_List.Count(); col++)

            {

                XmlElement tmp_Elm = doc.CreateElement(P_List[col].Name);

 

                string[] columnNames = stu_data.Columns.Cast<DataColumn>()

                             .Select(x => x.ColumnName)

                             .ToArray();

 

                tmp_Elm.InnerText = columnNames[col].ToString();

                student.AppendChild(tmp_Elm);

            }

            STUDENT_INF.AppendChild(student);        

 

            return STUDENT_INF;

        }

    }

}

 

Colored by Color Scripter

cs

 

School.cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace XMlTest
{
    public class School
    {
        public string SCHOOL_NAME { get; set; }
        public string SCHOOL_ADDRESS { get; set; }
        public string SCHOOL_STUDENT_COUNT { get; set; }
    }
}
 
cs


Student.cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace XMlTest
{
    public class Student
    {
        public string STUDENT_NAME { get; set; }
        public string STUDENT_GRADE { get; set; }
    }
}
 
cs


그리고 실행을 해보면 아래와 같이 XML 파일이 제대로 생성되었고,

내용 또한 제대로 기록 된 것을 알 수 있습니다.


실행 결과


다음에 또 XML 파일을 생성할 일이 생기면 이 포스팅을 참고해야겠다~~ㅎㅎ


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY