using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Web;
using System.Net;
using System.IO;
namespace WinFormEx
{
public partial class Ex05 : Form
{
public Ex05()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SearchBook();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
SearchBook();
}
}
private void SearchBook()
{
try
{
panel2.Controls.Clear();//초기화
//http://openapi.naver.com/search?key=7a6113b7791ce0313cb577f437131e3d&query=검색어&display=50&start=1&target=book
string search = textBox1.Text.Trim();
XmlDocument doc = new XmlDocument();
doc.Load(string.Format("http://openapi.naver.com/search?key=7a6113b7791ce0313cb577f437131e3d&query={0}&display=50&start=1&target=book", search));
//MessageBox.Show(doc.OuterXml);
//richTextBox1.Text = doc.OuterXml;
XmlNodeList result = doc.SelectNodes("//item");
int x = 10, y = 10;
foreach (XmlElement item in result)
{
//결과 <item> 1개당 -> BookItem유저컨트롤 1개
BookItem book = new BookItem();
book.labelTitle.Text = item.FirstChild.InnerText.Replace("<strong>", "").Replace("</strong>", "");//제목
book.groupBox1.Text = item.FirstChild.InnerText.Replace("< strong >", "").Replace("</strong>", "");
//book.labelLink.Text
book.labelAuthor.Text = item.ChildNodes[3].InnerText;//저자
//"90000" -> "90,000원"
string price = string.Format("{0:N0}원", int.Parse(item.ChildNodes[4].InnerText));
book.labelPrice.Text = price;//가격
book.labelISBN.Text = item.ChildNodes[8].InnerText;//ISBN
book.labelPublisher.Text = item.ChildNodes[6].InnerText;
string date = item.ChildNodes[7].InnerText;//20120501
book.labelPubdate.Text = string.Format("{0}년 {1}월 {2}일", date.Substring(0, 4), date.Substring(4, 2), date.Substring(6, 2));
//사진
// - 윈폼은 URL주소 형식의 이미지 출력 X
//Bitmap img = new Bitmap(item.ChildNodes[2].InnerText);
WebRequest request = WebRequest.Create(item.ChildNodes[2].InnerText);
WebResponse response = request.GetResponse();
Stream rs = response.GetResponseStream();
Bitmap img = new Bitmap(rs);
book.pictureBox1.Image = img;
//링크 걸기
book.labelLink.Tag = item.ChildNodes[1].InnerText;
book.labelLink.LinkClicked += new LinkLabelLinkClickedEventHandler(labelLink_LinkClicked);
//BookItem을 Panel1의 자식으로 추가
panel2.Controls.Add(book);
//유저 컨트롤 위치 선정
book.Location = new Point(x, y);
y += 200;
}
panel2.Height = y + 200;//**
vScrollBar1.Maximum = y - 200;
}
catch { }
}
void labelLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//브라우저 호출
System.Diagnostics.Process.Start("iexplore.exe", ((LinkLabel)sender).Tag.ToString());
}
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
//vScrollBar1.Value -> Panel2의 -Y좌표값
panel2.Location = new Point(0, -vScrollBar1.Value);
}
private void Ex05_Load(object sender, EventArgs e)
{
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace WinFormEx
{
public partial class Ex04 : Form
{
public Ex04()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//http://openapi.naver.com/search?key=7a6113b7791ce0313cb577f437131e3d&query=nexearch&target=rank
XmlDocument doc = new XmlDocument();
doc.Load("http://openapi.naver.com/search?key=7a6113b7791ce0313cb577f437131e3d&query=people&target=ranktheme");
//doc.Load("http://openapi.naver.com/search?key=&query=people&target=rank");
XmlElement item = doc.DocumentElement.FirstChild as XmlElement;
int n = 1;
listView1.Items.Clear();//**
foreach (XmlElement rn in item.ChildNodes)
{
ListViewItem vItem = new ListViewItem(n.ToString());//순위
vItem.SubItems.Add(rn.FirstChild.InnerText);//검색어
vItem.SubItems.Add(rn.ChildNodes[1].InnerText);//변동
n++;
listView1.Items.Add(vItem);
}
}
private void Ex04_Load(object sender, EventArgs e)
{
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace WinFormEx
{
public partial class Ex03 : Form
{
private XmlDocument doc;
public Ex03()
{
InitializeComponent();
doc = new XmlDocument();
}
private void Ex03_Load(object sender, EventArgs e)
{
doc.Load("memo.xml");
ShowXml();
}
private void ShowXml()
{
comboBox1.Items.Clear();
XmlDocument doc2 = new XmlDocument();
doc2.PreserveWhitespace = true;//**
doc2.Load("memo.xml");
richTextBox1.Text = doc2.OuterXml;
//메모 제목을 콤보박스에 추가
foreach (XmlElement item in doc.DocumentElement.ChildNodes)
{
MemoItem m = new MemoItem();
m.Title = item.FirstChild.InnerText;
m.No = item.GetAttribute("no");
comboBox1.Items.Add(m);
comboBox1.DisplayMember = "Title";
}
}
private void button1_Click(object sender, EventArgs e)
{
//문서의 구성요소 생성은 문서객체가 한다.
// - Javascript : document
// - document.createElement("태그명");
// - C# : XmlDocument
//1. <item>
XmlElement item = doc.CreateElement("item");
//2. <title>
XmlElement title = doc.CreateElement("title");
//3. <content>
XmlElement content = doc.CreateElement("content");
//4. <regdate>
XmlElement regdate = doc.CreateElement("regdate");
//5. 1 = 2 + 3 + 4
item.AppendChild(title);
item.AppendChild(content);
item.AppendChild(regdate);
//6. PCDATA 넣기
title.InnerText = textBox1.Text;
XmlText txt = doc.CreateTextNode(textBox2.Text);
content.AppendChild(txt);
regdate.InnerText = DateTime.Now.ToShortDateString();
//7. 속성 <item no="m1">
// a. 마지막 메모 가져오기
XmlElement lastMemo = doc.DocumentElement.LastChild as XmlElement;
// b. 메모의 no 속성값 가져오기 -> "m1"
string no = lastMemo.GetAttribute("no");
// c. no를 +1
// "m1" -> "1"
// - 새로운 메모의 번호
int index = int.Parse(no.Replace("m", "")) + 1;
// d. 새로운 메모번호를 <item>속성으로 추가하기
item.SetAttribute("no", "m" + index);
//8. <item>을 루트에 추가하기
doc.DocumentElement.AppendChild(item);
//----------------메모리 작업..
//9. memo.xml에 반영.. 저장하기
// - 메모리상의 Xml 트리구조를 모두 문서화시켜서 물리적인 xml파일에 저장
doc.Save("memo.xml");
//10.
ShowXml();
}
private void button2_Click(object sender, EventArgs e)
{
//문서 생성하기(memo2.xml)
//1. doc
XmlDocument doc = new XmlDocument();
//2. 읽어오기, 생성하기..
//Xml 선언문
XmlProcessingInstruction pi = doc.CreateProcessingInstruction("xml", "version='1.0' encoding='utf-8'");
//3. 모든 구성요소는 doc이하에 포함
doc.AppendChild(pi);
//주석
XmlComment cmt = doc.CreateComment("memo2.xml");
doc.AppendChild(cmt);
//루트
XmlElement list = doc.CreateElement("list");
doc.AppendChild(list);
//<item>
for (int i = 1; i <= 5; i++)
{
XmlElement item = doc.CreateElement("item");
XmlElement title = doc.CreateElement("title");
XmlElement content = doc.CreateElement("content");
XmlElement regdate = doc.CreateElement("regdate");
//CDATASection : 이영역은 XML 구성요소가 와도 문법으로 인식을 안한다. 그래서 주로 사용자가 입력한 데이터를 관리할때 사용한다.
//title.InnerText = "메모입니다.";//X
XmlCDataSection ctitle = doc.CreateCDataSection("<item> 태그 연습중..");
title.AppendChild(ctitle);
//content.InnerText//X
XmlCDataSection cContent = doc.CreateCDataSection("<item> 내용입니다...");
content.AppendChild(cContent);
regdate.InnerText = DateTime.Now.ToShortDateString();
//속성
item.SetAttribute("no", "m" + i);
//결합
item.AppendChild(title);
item.AppendChild(content);
item.AppendChild(regdate);
list.AppendChild(item);
}
//MessageBox.Show(doc.OuterXml);
doc.Save("memo2.xml");
}
private void button3_Click(object sender, EventArgs e)
{
//선택된 메모 찾기
// - 선택된 메모의 no값을 가지고 있는 <item> 찾기
MemoItem m = comboBox1.SelectedItem as MemoItem;
XmlElement item = doc.SelectSingleNode(string.Format("//item[@no='{0}']", m.No)) as XmlElement;
//수정하기
item.FirstChild.InnerText = "수정함";
doc.Save("memo.xml");
ShowXml();
}
private void button4_Click(object sender, EventArgs e)
{
//삭제
MemoItem m = comboBox1.SelectedItem as MemoItem;
XmlElement item = doc.SelectSingleNode(string.Format("//item[@no='{0}']", m.No)) as XmlElement;
doc.DocumentElement.RemoveChild(item);
doc.Save("memo.xml");
ShowXml();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
namespace WinFormEx
{
public partial class Ex02 : Form
{
public Ex02()
{
InitializeComponent();
}
private void 블로그관리ToolStripMenuItem_Click(object sender, EventArgs e)
{
//팝업
Ex02_url sub = new Ex02_url();
sub.Owner = this;
sub.Show();
}
private void Ex02_Load(object sender, EventArgs e)
{
//메인 로드
//1. blog.dat 읽기 -> Text
//2. 등록된 피드의 제목 읽기 -> XML
//3. 제목을 콤보박스 추가
ShowList();
}
public void ShowList()
{
comboBox1.Items.Clear();
StreamReader reader = new StreamReader("blog.dat");
string txt = "";
//1.
while ((txt = reader.ReadLine()) != null)
{
//2.
XmlDocument doc = new XmlDocument();
doc.Load(txt);
string title = doc.DocumentElement.FirstChild.FirstChild.InnerText;
comboBox1.Items.Add(new BlogItem { Title = title, URL = txt });
comboBox1.DisplayMember = "Title";
}
reader.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listView1.Items.Clear();//초기화
//블로그 선택 -> URL
BlogItem item = comboBox1.SelectedItem as BlogItem;
XmlDocument doc = new XmlDocument();
doc.Load(item.URL);
//포스트 정보 -> ListView에 출력
//카테고리, 타이틀, 날짜 -> <item>의 자식
XmlNodeList list = doc.SelectNodes("//item");
foreach (XmlElement post in list)
{
//post 하나당 제목,카테고리,날짜 가져와서 리스트뷰 아이템으로 추가하기
string category = post.ChildNodes[1].InnerText;
string title = post.ChildNodes[2].InnerText;
string date = post.ChildNodes[6].InnerText;
string link = post.ChildNodes[3].InnerText;
ListViewItem lItem = new ListViewItem(category);
lItem.SubItems.Add(title);
//Tue, 01 May 2012 16:53:28 +0900
DateTime regDate = DateTime.Parse(date);
lItem.SubItems.Add(regDate.ToString());
//guid or link
lItem.Tag = link;
listView1.Items.Add(lItem);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
//포스트 중 1개를 선택 -> 선택된 아이템 -> Tag -> 브라우징
if (listView1.SelectedItems.Count > 0)
{
string link = listView1.SelectedItems[0].Tag.ToString();
if (브라우저로보기ToolStripMenuItem.Checked)
{
webBrowser1.Navigate(link);
}
else
{
//문서로드 -> item중에.. 우리가 원하는 item찾기(현재 보고있는 글) -> 왜? -> 그안에 있는 글내용(description) 엘리먼트의 값을 얻기위해서..
XmlDocument doc = new XmlDocument();
BlogItem item = comboBox1.SelectedItem as BlogItem;
doc.Load(item.URL);
XmlElement desc = doc.SelectSingleNode("//item[link='" + link + "']/description") as XmlElement;
richTextBox1.Text = desc.InnerText;
}
}
}
private void 브라우저로보기ToolStripMenuItem_Click(object sender, EventArgs e)
{
브라우저로보기ToolStripMenuItem.Checked = true;
rSS보기ToolStripMenuItem.Checked = false;
webBrowser1.Visible = true;
richTextBox1.Visible = false;
}
private void rSS보기ToolStripMenuItem_Click(object sender, EventArgs e)
{
브라우저로보기ToolStripMenuItem.Checked = false;
rSS보기ToolStripMenuItem.Checked = true;
webBrowser1.Visible = false;
richTextBox1.Visible = true;
}
}
}
url
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
namespace WinFormEx
{
public partial class Ex02_url : Form
{
private FileInfo file;
public Ex02_url()
{
InitializeComponent();
}
private void Ex02_url_Load(object sender, EventArgs e)
{
file = new FileInfo("blog.dat");
ShowList();
}
private void ShowList()
{
//초기화
listBox1.Items.Clear();
//blog.dat에 있는 주소를 로드 -> ListBox 출력
StreamReader reader = file.OpenText();
string txt = "";
while ((txt = reader.ReadLine()) != null)
{
//listBox1.Items.Add(txt);//URL X
XmlDocument doc = new XmlDocument();
doc.Load(txt);
//블로그 제목
string title = doc.DocumentElement.FirstChild.FirstChild.InnerText;
BlogItem item = new BlogItem();
item.Title = title;
item.URL = txt;
listBox1.Items.Add(item);
listBox1.DisplayMember = "Title";
}
reader.Close();
}
private void button1_Click(object sender, EventArgs e)
{
//추가하기
//StreamWriter writer = null;
//if (file.Exists)
//{//있을때.. -> 추가모드 열기(Append)
// writer = file.AppendText();
//}
//else
//{//없을때.. -> 생성모드 열기(Create)
//}
//이미 등록된 주소를 필터링!!
foreach (BlogItem item in listBox1.Items)
{
if (item.URL == textBox1.Text)
{
MessageBox.Show("이미 등록된 피드입니다!!");
return;
}
}
StreamWriter writer = file.CreateText();
//1. 리스트박스의 블로그 주소를 기록
foreach (BlogItem item in listBox1.Items)
{
writer.WriteLine(item.URL);
}
//2. 새로운 텍스트박스의 주소를 기록
writer.WriteLine(textBox1.Text);
writer.Close();
//3. 리스트박스 갱신
ShowList();
textBox1.Text = "";
textBox1.Focus();
//4. 부모의 콤보박스 갱신
((Ex02)this.Owner).ShowList();
}
private void button2_Click(object sender, EventArgs e)
{
//삭제 -> 선택된 피드
//1. 리스트박스에서 항목 삭제
//2. 리스트박스에 등록된 주소만을 blog.dat에 다시 기록
if (listBox1.SelectedIndex == -1)
return;
StreamWriter writer = file.CreateText();
listBox1.Items.RemoveAt(listBox1.SelectedIndex);//1.
//2.
foreach (BlogItem item in listBox1.Items)
{
writer.WriteLine(item.URL);
}
writer.Close();
ShowList();
//부모의 콤보박스 갱신
((Ex02)this.Owner).ShowList();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
BlogItem
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WinFormEx
{
class BlogItem
{
public string Title { get; set; }
public string URL { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml; //@@@@
namespace WinFormEx
{
public partial class Ex01 : Form
{
public Ex01()
{
InitializeComponent();
}
private void Ex01_Load(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
//블로그의 rss 단추를 누른수 다음의 주소를 붙여넣기
doc.Load("http://petit_ange.blog.me/rss");
//Console.WriteLine(doc.OuterXml);
XmlNodeList result = doc.SelectNodes("//item/title");
foreach (XmlElement title in result)
{
//listBox1.Items.Add(title.InnerText);
string txt = title.InnerText;//제목만 들어있음
string url = title.NextSibling.InnerText;//타이틀의 다음형제가 url 이므로..
//@@@@@listbox는 하나의 값만 넣을 수 있으므로 다음의 방법들 중에서
// 하나를 이용하여 변형
//1. 익명 객체 이용
//listBox1.Items.Add(new { Txt = txt, Url = url });
//2. 클래스를 아래에 정의하고 객체를 만들어 이용
Item item = new Item();
item.Txt = txt;
item.Url = url;
//Item item = new Item { Txt = txt, Url = url });//위의 3줄과 같다.
listBox1.Items.Add(item);
//리스트박스에 둘중에 하나만 보여준다.
listBox1.DisplayMember = "Txt";
//listBox1.ValueMember = "Url";
//listBox1.DisplayMember = "Url";
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
Item item = listBox1.SelectedItem as Item;
//MessageBox.Show(item.Url);
System.Diagnostics.Process.Start("iexplore.exe", item.Url);
}
class Item
{
//자동화 프로퍼티
public string Txt { get; set; }
public string Url { get; set; }
}
}
}
<주소록>
<회원 번호="1">
<이름>홍길동</이름>
<나이>20</나이>
<전화번호>010-3333-4444</전화번호>
<주소>
<우편번호>110-111</우편번호>
<상세주소>서울시 영등포구</상세주소>
</주소>
</회원>
<회원 번호="2">
<이름>아무게</이름>
<나이>25</나이>
<전화번호>010-555-4554</전화번호>
<주소>
<우편번호>120-222</우편번호>
<상세주소>서울시 서대문구</상세주소>
</주소>
</회원>
<회원 번호="3">
<이름>테스트</이름>
<나이>30</나이>
<전화번호>010-555-4554</전화번호>
<주소>
<우편번호>120-222</우편번호>
<상세주소>서울시 서대문구</상세주소>
</주소>
</회원>
<회원 번호="4">
<이름>이순신</이름>
<나이>28</나이>
<전화번호>010-555-4554</전화번호>
<주소>
<우편번호>120-222</우편번호>
<상세주소>서울시 서대문구</상세주소>
</주소>
</회원>
<회원 번호="5">
<이름>하하하</이름>
<나이>21</나이>
<전화번호>010-555-4554</전화번호>
<주소>
<우편번호>120-222</우편번호>
<상세주소>서울시 서대문구</상세주소>
</주소>
</회원>
</주소록>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; //@@@@ namespace ConsoleEx { class Ex18_XPath { static void Main(string[]
args) { //XPath // - XML문서내에서 원하는 노드를 찾기 위한 탐색 언어 // Axis + NodeTest +
Predicate //NodeTest //(1) / // - 루트 // - /주소록/회원/이름 // - 절대경로 //(2) . // - 상대경로 // - 회원/이름 // - ./회원/이름 //(3) .. // - 상대경로 // - 부모노드 // - ../노드명/노드명/../노드명 //(4) // // - 문서 전체를 대상으로 검색 // - //이름 : 부모자식 상관없이 엘리먼트명이 "이름"인 노드를 모두 변환 //(5) @속성명 // - 속성 // - /주소록/회원/@번호
; 속성도 자식취릅을 하므로 \ 붙임 //(6) //@속성명 // - //@번호 : 부모자식, 어떤 엘리먼트에 속한 속성이던지 상관없이 속성명만 "번호"이면 모두 반환 //Predicate //(1) //회원[이름] // - 모든 "회원" 엘리먼트 중에서.. 자식 엘리먼트로 "이름"이라는 자식을 갖는 회원... // - 자식의 유무를 조건** //(2) //회원[@번호] // - 모든 "회원" 엘리먼트 중에서.. "번호"라는 속성을 갖는 회원만... // -ex) //div[@class] //(3) //회원[이름='홍길동'] // - 회원 중 자식(이름)의 PCDATA가 홍길동인 회원 //(4) //회원[@번호='2'] // - 회원 중 자식(속성)의 CDATA값이 2인
회원 //(5-1) //회원[나이 > 20] //(5-2) //회원[@번호 < 3] // - 기본적인 연산자 지원 //(6-1) //나이[. > 25] ; 나이[나이 > 25] 의 뜻이다..본인은 점(.) 으로 표현 //(6-2) //@번호[. = 2] ; 속성도 자기 자신은 점(.) //(7-1) //회원[@번호 = 2]/이름/text() ; 회원번호가 2인 사람의 이름 엘리먼트의 PCDATA 반환 //(7-2) //이름 : 이름 엘리먼트 배열 반환 //(7-3) //이름/text() : 이름 문자열 배열
반환 //(8) //회원[position() = 2] // - 모든 회원 중 2번째 회원 반환 XmlDocument
doc = new XmlDocument(); doc.Load(@"..\..\address.xml"); //문서상의 모든 "이름" 을 출력 //1. dom 방식 XmlElement
root = doc.DocumentElement; XmlNodeList ms
= root.ChildNodes;//<회원> 태그들의 집합 foreach (XmlElement m in
ms) { //<회원>의 첫번째 자식 = <이름> Console.WriteLine(m.FirstChild.InnerText); } Console.Clear(); //2. XPath 방식 //doc.SelectNodes("//이름"); //XmlNodeList ms2 =
doc.SelectNodes("//이름"); XmlNodeList
ms2 = doc.SelectNodes("//회원[나이 > 25]/이름");//
나이가 25 넘는 사람의 이름만 반환 foreach (XmlElement m in
ms2) { //위와는 다르게 여기서 m은 자체가 이름이다. Console.WriteLine(m.InnerText); } Console.Clear(); //문제:이름이 테스트인놈의 상세주소 //모든 이름(자기자신)이 테스트인놈의 상세주소. 그러나 이름과 주소는 형제관계임에 주의 XmlNodeList
result = doc.SelectNodes("//이름[.='테스트']/../주소/상세주소"); foreach (XmlElement item in
result) { //<상세주소> Console.WriteLine(item.InnerText); } Console.Clear(); //위의 컬렉션들과는 다르게 아래는 단일값 반환 //foreach 문은 자동으로 형변환을 시켜주지만, 아래와같이하면
형변환까지도 해줘야 함. XmlElement
address = doc.SelectSingleNode("//이름[.='테스트']/../주소/상세주소") as
XmlElement; Console.WriteLine(address.InnerText); } } }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml; //@@@@
namespace ConsoleEx
{
class Ex19_XPath
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
//블로그의 rss 단추를 누른수 다음의 주소를 붙여넣기
doc.Load("http://petit_ange.blog.me/rss");
//Console.WriteLine(doc.OuterXml);
//포스트 제목 출력
//item 엘리먼트의 자식으로 title를 갖는놈들만
XmlNodeList list = doc.SelectNodes("//item/title");
foreach (XmlElement item in list)
{
Console.WriteLine(item.InnerText);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml; //@@@@
namespace ConsoleEx
{
class Ex17_DOM
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"..\..\address.xml");
//루트 찾기
XmlElement root = doc.DocumentElement;
XmlElement m2 = root.ChildNodes[1] as XmlElement;
//m2
//<회원 번호="2">
//*** 현재 노드의 타입은? NodeType
Console.WriteLine(m2.NodeType);//Element 출력
Console.WriteLine(m2.FirstChild.FirstChild.NodeType); //Text 출력
Console.WriteLine(m2.HasAttributes);
Console.WriteLine(m2.HasChildNodes);
Console.WriteLine(m2.IsEmpty); //단톡 태그인지 확인
//속성 접근
//m2가 가지는 회원번호는? GetAttribute
Console.WriteLine(m2.GetAttribute("번호"));// GetAttribute: 속성값을 반환
XmlAttribute no = m2.GetAttributeNode("번호");//GetAttributeNode: 위와는 다르게 그 속성 자체를 반환
//Console.WriteLine(no);
Console.WriteLine(no.Value);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml; //@@@@
namespace ConsoleEx
{
class Ex16_blog
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
//블로그의 rss 단추를 누른수 다음의 주소를 붙여넣기
doc.Load("http://petit_ange.blog.me/rss");
//Console.WriteLine(doc.OuterXml);
//블로그 포스트의 제목을 출력해보자.
//1. 루트 엘리먼트 접근
XmlElement rss = doc.DocumentElement;
//2. <channel> ; 첫번째 자식이자 마지막 자식인놈
XmlElement channel = rss.FirstChild as XmlElement;
//3. 탐색(item까지); channel태그의 자식들..
foreach (XmlElement item in channel.ChildNodes)
{
//Console.WriteLine(item.Name);
if (item.Name == "item")
{
XmlElement title = item.ChildNodes[2] as XmlElement;
Console.WriteLine(title.InnerText);
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;//C#에서 XML을 다룰수 있도록하는 조작 클래스들이 있음.
namespace ConsoleEx
{
class Ex14_DOM
{
static void Main(string[] args)
{
//DOM(Document Object Model)
// - Javascript DOM : 브라우저에서
// - C# DOM : 브라우저를 제외한 윈폼, 웹폼, 서비스....
//C#으로 XML 조작
// 1. SAX(StreamReader ... 방식)
// 2. DOM
//DOM 처리순서
// 1. 문서를 읽기(문서 전체를 한번에...)
// 2. 문서내의 구성요소(엘리먼트, 속성, PCDATA, 엔티티, 주석, 처리지시문 등..)을 객체로 생성해서
// 부모자식 관계를 형성시킨다.(트리구조를 만듦) ************************
// 3. 메모리상의 트리구조를 통해서 원하는 요소에 접근, 조작(읽기, 수정, 삭제, 추가 등...)
//DOM의 장점
// 1. 조작 편함
// 2. 원하는 노드 접근 용이
// 3. 속도 빠름
// 4. 같은 요소를 반복해서 접근해도 용이함..
// 5. XPath지원(XML 검색 언어)
//DOM 단점
// 1. 무거움(문서 전체를 Object화 로드...)
//address.xml 읽기
// 1. 문서 매핑 객체 생성(문서와 동등한 역할 객체)
// - 실제 xml를 총괄
// - 문서의 구조를 조작(생성, 삭제)
XmlDocument doc = new XmlDocument();
// 2. 읽기(전체) **********
// 경로: 부모폴더의 부모폴더로 이동
doc.Load(@"..\..\address.xml");
// 3. 조작
// OuterXml : 현재 객체를 포함해서 자식들이 가지고 있는 모든 Xml 코드를 문자열로 반환
// InnerXml : 현재 객체를 포함하지 않고 자식들이 가지고 있는 모든 Xml 코드를 문자열로 반환
//Console.WriteLine(doc.OuterXml);
Console.WriteLine(doc.InnerXml);
}
}
}
2번째 DOM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml; //@@@
namespace ConsoleEx
{
class Ex15_DOM
{
static void Main(string[] args)
{
//DOM -> (조건)미리 XML파일의 구조와 의미 파악
//0. 파일에서 읽어와서 객체 doc에 저장
XmlDocument doc = new XmlDocument();
doc.Load(@"..\..\address.xml");
//기본 클래스
// 1. 엘리먼트(태그) -> XmlElement
// 2. 속성 -> XmlAttribute
// 3. PCDATA -> XmlText
// 4. 주석 -> XmlComment
// 5. XmlNode -> object와 비슷함. 대부분의 부모 클래스 역할을 함(XmlElement, XmlText로 다운캐스팅 해야 함)
//1. 문서의 루트 엘리먼트 저장(그러나, 하위의 모든 엘리먼트들도 가지고 있다.)
XmlElement root = doc.DocumentElement;
Console.WriteLine(root.Name);//최상위 "주소록" 엘리먼트명 출력
//2. 자식 엘리먼트 접근
// - firstChild. lastChild, childNodes
//XmlNode m1 = root.ChildNodes[0];
XmlElement m1 = (XmlElement)root.ChildNodes[0]; //회원
Console.WriteLine(m1.Name);
//Console.WriteLine(m1.OuterXml);
//3. 첫번째 자식에 접근
//XmlElement name = (XmlElement)m1.ChildNodes[0];
XmlElement name = (XmlElement)m1.FirstChild;//이름
Console.WriteLine(name.Name);
//3. PCDATA에 접근 방법1
Console.WriteLine(name.InnerText);
//3. PCDATA에 접근 방법2; 위와 같은 결과.
XmlText txt = (XmlText)name.FirstChild;
Console.WriteLine(txt.Value);// 이럴때는 txt도 엘리멘트로 보기때문에innetText대신에 .Value도 됨
//1번째 자식
//m1.ChildNodes[i]
//1번째 자식
//m1.FirstChild
//막내자식
//m1.LastChild
Console.WriteLine();
//형제 NextSibling;다음형제 PreviousSibling;이전형제
//XmlElement m2 = root.ChildNodes[1] as XmlElement;
XmlElement m2 = m1.NextSibling as XmlElement;
Console.WriteLine(m2.FirstChild.InnerText);
//m2.PreviousSibling //이전형제
//부모
XmlElement 주소록 = m1.ParentNode as XmlElement;
Console.WriteLine(주소록.Name);
}
}
}