심재운 블로그

728x90
반응형
동일한 node 가 존재할 경우, childNode 함수를 통해 foreach 의 루프구문을 통해 데이터를 추출할 수 있다.



<!--?xml version="1.0" encoding="utf-8" ?-->
<videos>
<video>
<title>The Distinguished Gentleman</title>
<director>Jonathan Lynn</director>
<castmembers>
<actor>Eddie Murphy</actor>
<actor>Lane Smith</actor>
<actor>Sheryl Lee Ralph</actor>
<actor>Joe Don Baker</actor>
<actor>Victoria Rowell</actor>
</castmembers>
<length>112 Minutes</length>
<format>DVD</format>
<rating>R</rating>
</video>
<video>
<title>Her Alibi</title>
<director>Bruce Beresford</director>
<length>94 Mins</length>
<format>DVD</format>
<rating>PG-13</rating>
</video>
<video>
<title>Chalte Chalte</title>
<director>Aziz Mirza</director>
<length>145 Mins</length>
<format>DVD</format>
<rating>N/R</rating>
</video>
</videos>

 

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

namespace VideoCollection
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(strFilename))
            {
                xmlDoc.Load(strFilename);
                // Locate the root node and 
                // get a reference to its first child
                XmlNode node = xmlDoc.DocumentElement.FirstChild;
                // Create a list of the child nodes of 
                // the first node under the root
                XmlNodeList lstVideos = node.ChildNodes;

                // Visit each node
                for (int i = 0; i < lstVideos.Count; i++)
                {
                    // Look for a node named CastMembers
                    if (lstVideos[i].Name == "CastMembers")
                    {
                        // Once/if you find it,
                        // 1. Access its first child
                        // 2. Create a list of its child nodes
                        XmlNodeList lstActors =
                            lstVideos[i].ChildNodes;
                        // Display the values of the nodes
                        for (int j = 0; j < lstActors.Count; j++)
                            Console.WriteLine("{0}",
                                lstActors[j].InnerText);
                    }
                }
            }
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

            Console.WriteLine();
            return 0;
        }
    }
}

출력 Eddie Murphy Lane Smith Sheryl Lee Ralph Joe Don Baker Victoria Rowell


728x90
반응형

이 글을 공유합시다

facebook twitter kakaoTalk kakaostory naver band

본문과 관련 있는 내용으로 댓글을 남겨주시면 감사하겠습니다.

비밀글모드