ㅊㅊ : 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파
'C#' 카테고리의 다른 글
C# 에서 string 타입으로 숫자가 저장되어 있을때 int 타입으로 변경 (0) | 2019.06.26 |
---|---|
C#에서 XML파일 만들고 자식노드 핸들링해보기(remove) (0) | 2019.06.26 |
C#에서 XML파일 만들고 자식노드 핸들링해보기(replace) (0) | 2019.06.26 |
[공유] C# new & override (뉴 & 오버라이드) (0) | 2019.06.26 |
c# Window Form TreeView 삭제/추가/노드개수 (0) | 2019.06.26 |