.NET/XML.NET

[XML.NET C# 소스] XmlReader 개체로 요소 읽기

언제나휴일 2016. 4. 18. 15:52
반응형

 XmlReader 개체로 요소 읽기


Program.cs


data.xml


class Book

{

    internal string Title

    {

        get;

        private set;

    }

    internal int Price

    {

        get;

        private set;

    }

    internal static Book MakeBook(XmlReader xr)

    {

        string title = string.Empty;

        int price = 0;

        xr.ReadToDescendant("title");

        title = xr.ReadElementString("title");

        xr.ReadToNextSibling("price");

        xr.ReadStartElement("price");

        price = int.Parse(xr.Value);

        return new Book(title, price);

    }

    Book(string title, int price)

    {

        Title = title;

        Price = price;

    }

    public override string ToString()

    {

        return Title;

    }

}

class Program

{

    static void Main(string[] args)

    {

        ArrayList ar = new ArrayList();

        XmlReader reader = XmlReader.Create("data.xml");

        while (reader.Read())

        {

            if (reader.IsStartElement("book"))

            {

                Book book = Book.MakeBook(reader);

                if (book != null)    {    ar.Add(book);    }

            }

        }

        Console.WriteLine("도서 개수:{0}", ar.Count);

        foreach (Book book in ar)

        {

            Console.WriteLine("도서명:{0} 가격:{1}", book.Title, book.Price);

        }

    }

}

[소스] XmlReader 개체로 요소 읽기 예제 코드

 

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

<books xmlns="urn:books-schema">

  <book>

    <title>XML.NET</title>

    <price>12000</price>

  </book>

  <book>

    <title>ADO.NET</title>

    <price>15000</price>

  </book>

</books>

[문서] data.xml 문서 내용



언제나 휴일 티스토리 바로가기

무료 동영상 강의 유튜브 채널 바로가기

반응형