2012-06-13

C# xml 데이터로 treeview 형태로 표현하기


출처: http://support.microsoft.com/kb/317597/ko



xmlDoc.Load("sample.xml");
XmlDocument xmlDoc = new XmlDocument();
treeView1.Nodes.Add(new TreeNode(xmlDoc.DocumentElement.Name)); //root node(family)를 treeview1에 업데이트
TreeNode tnode = new TreeNode(); //root node에 붙일 node 초기화
tnode=treeView1.Nodes[0]; // 0번 node에 tnode를 붙임

AddNode(xmlDoc.DocumentElement, tnode); //재귀호출
---------------------------------

        ///

        /// XmlNode로 부터 TreeNode를 기록하는 Recursive call.
        /// AddNode가 받을 TreeNode와 XmlNode parameter를 A와 B로 변경
        /// 재귀호출에 쓰일 TreeNode와 XmlNode를 AA와 BB로 변경함.
        ///

        /// 재귀탐색을 할 XmlNode
        /// 재귀기록을 할 TreeNode
        private void AddNode(XmlNode A,TreeNode B)
        {

             XmlNode AA;   //AddNode를 재귀호출 할 때 쓰일 XmlNode
             TreeNode BB;  //AddNode를 재귀호출 할 때 쓰일 TreeNode
             XmlNodeList xmlNodes; //A 밑의 ChildNodes를 저장할 컬렉션
             int i; // Child의 수만큼 재귀반복 할 count

             // Loop through the XML nodes until the leaf is reached.
             // Add the nodes to the TreeView during the looping process.
             if (A.HasChildNodes) //A가 child를 가지고 있으면 재귀호출하며 마지막 노드를 찾음.
             {
                xmlNodes = A.ChildNodes; // A child노드들을 노드컬렉션(xmlNodes)에 등록
                for(i = 0; i<=xmlNodes.Count - 1; i++) //xmlNodes의 수 많큼 반복
                {
                   AA = A.ChildNodes[i]; // A의 child노드를 하나씩 재귀호출에 쓰일 AA에 저장
                   B.Nodes.Add(new TreeNode(AA.Name)); //TreeNode B에 AA항목(node) 추가
                   BB = B.Nodes[i];//AA.Name으로 추가된 TreeNode를 다음 재귀호출에 쓰일 BB로 저장
                   AddNode(AA, BB); // AA와 BB로 재귀호출
                   B.Text = "!";
                }
             }
             else // child가 없는 leaf node(Xml의 tag가 아닌 Text에 해당)이면 B.Text에 XML태그 값을 저장
             {
                // Here you need to pull the data from the XmlNode based on the
                // type of node, whether attribute values are required, and so forth.
                B.Text = (A.OuterXml).Trim(); // A.OuterXml의 의미 없는 공백문자를 제거
             }
        }

-----------------------------------

댓글 없음:

댓글 쓰기