C#/Console

[C#] Xml 읽어오기 (System.Xml)

스타크래프트 좋아하는 사람 2025. 5. 23. 13:15

Xml 구조 읽는 방법 예제

 

결과

 

using System;
using System.Xml;

class Test
{
    static void Main()
    {
        string testData =
                "<main>" +
                " <sub attribute1=\"SubAttribute\">" +
                "  <field name=\"first\">1</field>" +
                "  <field name=\"second\">" +
                "   <test>" +
                "    2" +
                "   </test>" +
                "  </field>" +
                " </sub>" +
                "</main>";

        XmlDocument xml = new XmlDocument();

        //파일 경로로 읽는 방식
        //xml.Load("파일 경로");

        //string 읽는 방식
        xml.LoadXml(testData);

        //<sub> 가져오기
        XmlNode subNode = xml.SelectSingleNode("main/sub"); //첫 번째 노드 가져옴

        //<sub> attribute1 가져오기
        string attribute1 = subNode.Attributes["attribute1"]?.Value;
        Console.WriteLine($"attribute1 : {attribute1}");

        //<sub><field> 가져오기
        XmlNodeList fieldList = subNode.SelectNodes("field"); //Node의 Node 방식

        //<field> 값들 순회
        foreach (XmlNode node in fieldList)
        {
            string innterText = node.InnerText; //순수 값.
            string innerXml = node.InnerXml; //xml 값 전체

            Console.WriteLine($"innerText: {innterText}, innerXml: {innerXml}");
        }

        //번외) 항상 첫 번째 값을 가져옴 (field가 여러개)
        string x = subNode["field"].Attributes["name"]?.Value; //"first"
        Console.WriteLine($"first node : {x}");
    }
}