본문 바로가기
IT Study/C#

[C#] XML Convert to CSV

by dev_huhu 2021. 3. 13.
반응형

XmlDocument 클래스 사용해서 Xml Parsing을 해보자.


아래의 Xml 문서는 w3school에 예제로 있는 자료인데 직접 만들기 귀찮으니 활용했다.

<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>
   Two of our famous Belgian Waffles with plenty of real maple syrup
   </description>
    <calories>650</calories>
</food>
<food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>
    Light Belgian waffles covered with strawberries and whipped cream
    </description>
    <calories>900</calories>
</food>
<food>
    <name>Berry-Berry Belgian Waffles</name>
    <price>$8.95</price>
    <description>
    Belgian waffles covered with assorted fresh berries and whipped cream
    </description>
    <calories>900</calories>
</food>
<food>
    <name>French Toast</name>
    <price>$4.50</price>
    <description>
    Thick slices made from our homemade sourdough bread
    </description>
    <calories>600</calories>
</food>
<food>
    <name>Homestyle Breakfast</name>
    <price>$6.95</price>
    <description>
    Two eggs, bacon or sausage, toast, and our ever-popular hash browns
    </description>
    <calories>950</calories>
</food>
</breakfast_menu>

 

출처: www.w3schools.com/xml/default.asp

 

XML Tutorial

XML Tutorial XML stands for eXtensible Markup Language. XML was designed to store and transport data. XML was designed to be both human- and machine-readable. XML Example 2 <?xml version="1.0" encoding="UTF-8"?> <breakfast_menu> <food>     <name>Belgian

www.w3schools.com


파일 경로를 통해 xml을 읽어들이려면 XmlDocument 클래스의 LoadXml(xml) 부분을 고쳐서 Load(filepath) 메서드를 사용하면 된다.

 

LoadXml에서 쌍따옴표(")를 처리하기 귀찮으니 xml의 제일 위에 한 줄은 지우고 사용했다.

 

csv로 바꾸는데 xml파일에 description 노드에 콤마(,)가 포함되어 있길래 주석으로 지웠다.

using System;
using System.IO;
using System.Text;
using System.Xml;

namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {
            string csvContent = "";
            
            // csv 의 열 이름 정의
            csvContent += "name,price,calories\n";
            
            XmlDocument xml = new XmlDocument();
			
            // xml문서 로드
            xml.LoadXml("<breakfast_menu><food><name>Belgian Waffles</name><price>$5.95</price><description>Two of our famous Belgian Waffles with plenty of real maple syrup</description><calories>650</calories></food><food><name>Strawberry Belgian Waffles</name><price>$7.95</price><description>Light Belgian waffles covered with strawberries and whipped cream</description><calories>900</calories></food><food><name>Berry-Berry Belgian Waffles</name><price>$8.95</price><description>Belgian waffles covered with assorted fresh berries and whipped cream</description><calories>900</calories></food><food><name>French Toast</name><price>$4.50</price><description>Thick slices made from our homemade sourdough bread</description><calories>600</calories></food><food><name>Homestyle Breakfast</name><price>$6.95</price><description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description><calories>950</calories></food></breakfast_menu>");
            
            // food 태그를 사용하는 노드들을 XmlNodeList로 가져옴
            XmlNodeList xmlList = xml.GetElementsByTagName("food");

            // XmlNodeList에서 XmlNode를 가져온 후 처리
            foreach (XmlNode node in xmlList)
            {
                string name = node["name"].InnerText;
                string price = node["price"].InnerText;
                //string description = node["description"].InnerText;
                string calories = node["calories"].InnerText;

                csvContent +=
                    name + ","
                    + price + ","
                    //+ description + ","
                    + calories + "\n";
            }
            
            // xml에서 읽은 내용 콘솔 출력
            Console.WriteLine(csvContent);
            
            // csv 파일로 저장하기
            string path = "C:\\Users\\hsg46\\OneDrive\\Desktop\\h";
            string fileName = "\\파일이름.csv";

            File.WriteAllText(path + fileName, csvContent, Encoding.Default);

        } // end of main()
    }
}

실행해보니 콘솔창에 잘 찍히고 csv 파일도 잘 만들어졌다.

 

 

 


사실 xml 파일 관련한 업무를 하는데.. 자동화 할 방법을 생각하다가 XmlDocument를 활용하여 업무를 수행했다.

 

여러 폴더 안에 있는 xml 처리였는데 파일 관련 클래스들을 적절히 활용해서 반복문 돌리니까 수월하게 일을 마칠 수 있었다.

  • System.IO.FileInfo
  • System.IO.File
  • System.IO.DirectoryInfo
  • System.IO.Directory

 

반응형

댓글