기록
Published 2019. 6. 26. 14:17
C#에서 XML파일 탐색하기. C#
728x90

ㅊㅊ : http://funny7103.blog.me/90027733483

 

1. 임의의 XML 파일을 가져오고 안의 내용을 탐색해 보자.

 

2. C# file

using System;
using System.Xml;

namespace ConsoleXML3
{
 public class Class2
 {
  public static void Main(string[] args)
  {
   XmlDocument doc = new XmlDocument();
   doc.Load("blog.xml");

   XmlNodeList items = doc.SelectNodes("//item");
   Console.WriteLine("포스트갯수 : " + items.Count);  // 15... 출력


//   XmlElement root = doc.DocumentElement;
//   Console.WriteLine(root.HasChildNodes + " - " + root.HasAttributes); // ture... 출력


   XmlElement root = doc.DocumentElement;
   Console.WriteLine(root.HasChildNodes + " - " + root.HasAttributes);
//   Console.WriteLine(root.OuterXml);      // <rss> 이하 모든 태그
//   Console.WriteLine(root.InnerXml);      // <rss> 의 자식&자손
//   Console.WriteLine(root.InnerText);    // <rss> 의 시작~끝태그 사이의 모든 텍스트O, 태그X


   // post에서의 Title만 찾고 싶다고 
   XmlNodeList titles = doc.SelectNodes("//item/title"); // 목적은 item 밑에있는 title 라는 거지.
   foreach(XmlNode title in titles) // title은 더이상 자식이 없어. title이 가진 #PCDATA를 가져오는거지.
   {
    Console.WriteLine(title.InnerText);
   }


   // 첫번째 자식인 post만 찾아보자
   XmlNode firstPost = doc.SelectNodes("//item")[0];
   Console.WriteLine("1 : " + firstPost.InnerText); // 첫번째 item이 가진 모든 #PCDATA를 가져왔어.


   // 두번째 자식을 가져오는 여러가지 방법 중 NextSibling
   XmlNode secondPost = firstPost.NextSibling; // 즉 자기랑 형제격인 노드를 탐색할 때..
   Console.WriteLine("2 : " + firstPost.InnerText);


   // secondPost 입장에서의 형은 secondPost.PrevioutSibling는 firstPost는 말하는거야.


   // 많이 쓰는 "부모노드" 찾기
   XmlNode parent = firstPost.ParentNode;  // <item>
   Console.WriteLine(parent.Name); // 출력되는 channel 이 firstPost의 보모노드겠지.


   // 노드 타입
   Console.WriteLine(parent.NodeType);   // Element..... 가 출력


   // 속성값
   Console.WriteLine("속성갯수 : " + root.Attributes.Count); // 4 
   XmlAttributeCollection attrs = root.Attributes;
   for (int i=0; i<attrs.Count; i++)
   {
    Console.WriteLine(attrs[i].Name + "=" + attrs[i].Value); // 속성값은 Value로 받아와야 해. 탐색용
   }


   // 이번에는 '버젼'이라는 속성을 받아올꺼야.
   XmlNodeList version = doc.SelectNodes("//rss/@version");
   Console.WriteLine(version[0].Name + "=" + version[0].Value); // XPath를 써도 상관이 없겠지. 검색용

  }
 }
}

[출처] [3] C#에서 XML파

profile

기록

@데굴데구르르 림

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

2025, 이제 사내 컨플루언스에 모두 작성하게 되어서 업데이트가 잘 없을 것 같습니다..