59.1 XElement 클래스를 사용하여 XML 요소를 생성하거나 가공하기

    이번에는 XML 데이터를 다루는 XElement 클래스를 사용해 보겠습니다. 다음 내용을 입력한 후 실행해 보세요. XElement 클래스는 XML 요소를 생성하거나 담을 수 있는 그릇입니다.

    XElement 클래스를 사용하여 XML 요소를 생성 및 가공: XElementDemo.cs

    using System;
    using System.Linq;
    using System.Xml.Linq;
    
    class XElementDemo
    {
        static void Main()
        {
            //① XML 요소 생성
            XElement category = new XElement("Menus",
                new XElement("Menu", "책"),
                new XElement("Menu", "강의"),
                new XElement("Menu", "컴퓨터")
            );
            Console.WriteLine(category);
    
            //② XML 요소 가공
            XElement newCategory = new XElement("Menus",
                from node in category.Elements()
                where node.Value.ToString().Length >= 2
                select node
            );
            Console.WriteLine(newCategory);
        }
    }

    실행 결과

    <Menus>
      <Menu>책</Menu>
      <Menu>강의</Menu>
      <Menu>컴퓨터</Menu>
    </Menus>
    <Menus>
      <Menu>강의</Menu>
      <Menu>컴퓨터</Menu>
    </Menus>

    XML 데이터를 다루는 클래스 중에서 XElement 클래스를 사용하여 XML 데이터를 만들고, XML 데이터에 LINQ를 사용하여 XML 요소를 가공합니다. 이 책에서 많이 이야기했지만, 지금 학습하는 시점에서는 ‘이러한 클래스도 있고 이렇게 하면 이러한 결과가 나오는구나’ 정도로 가볍게 살펴보고 넘어갑니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.