|
HTML Parsing(3) |
2011.05.23(월) |
작성자: 김택환 | |
HTML Parsing연습(3) |
※ 시력 장애가 있는 사람들은 그림을 보기 어려움으로 글로써 이를 알려주어야 할 것이다. 이에
HTML을 parsing하여 이미지에 alt태그의 속성이 들어가 있는지를 판별하고, 태그 속성을 넣어주는 프로그램을 통하여 HTML Parsing에 대하여 학습한다.
<Main 창>
private void SearchTestCaseData() { foreach (HtmlElement he in hinfo.Hec) { if (he.TagName.ToUpper() == "IMG"||he.TagName.ToUpper()=="IMAGE"|| he.TagName.ToUpper() == "AREA) //TagName:HTML 태그의 이름을 가져옴 //ToUpper:이 문자열의 복사본을 대문자로 변환하여 반환 //AREA : 하나의 이미지에서 링크 시킬 영역을 지정 { if (he.GetAttribute("alt") != "" && he.GetAttribute("alt") != " ") { //<img src="그림 주소" alt="그림이 없을 때 나올 설명" title="말풍선에 나올 설명" /> if (he.GetAttribute("href") != "" && he.GetAttribute("href") != " ") { string buf = he.GetAttribute("href"); SettingData(he, buf); } else if (he.GetAttribute("src") != "" && he.GetAttribute("src") != " ") { string buf = he.GetAttribute("src"); SettingData(he, buf); } } else {… … … …} } } } |
※ Image를 태그에 따라 분류 하여 데이터를 저장 한다.
private void SettingData(HtmlElement he, string buf) { WebClient wc = new WebClient(); string fname = string.Format("{0}", num++); path = hinfo.Path + fname + @".jpg"; wc.DownloadFile(buf, path); byte[] img = ChangeImage(path); HtmlData data = null; if (img != null) { data = new HtmlData(he.GetAttribute("alt"), img, he.OuterHtml); } … … … arr.Add(data); } |
※ DownloadFile을 이용하여 URI를 통하여 로컬파일에 리소스를 다운 받습니다. alt태그의 내용과 저장한 그림파일, 요소의 HTML코드를 저장합니다.
private void button1_Click(object sender, EventArgs e) { View(); } private void View() { try { if (cnt != arr.Count) { HtmlData he = arr[cnt++] as HtmlData; textBox2.Text = he.Alt; textBox1.Text = he.Source; MemoryStream ms = new MemoryStream(he.Img); Image image = Image.FromStream(ms); pictureBox1.Image = image; } else { MessageBox.Show("끝 입니다."); cnt = 0; } } catch { Bitmap bmp = new Bitmap(Image.FromFile(fullpath)); pictureBox1.Image = bmp; } } |
저장한 데이터를 보여 줍니다. catch문에서는 AREA는 Image가 아니기에 예외를 발생하는데 이때 처리 하기 위함 입니다.
<저장한 태그 속성을 확인하는 창>
void Document_Focusing(object sender, HtmlElementEventArgs e) {
HtmlDocument ae = (HtmlDocument)sender; HtmlElement hel = ae.ActiveElement;//현재 입력 포커스가 있는 HtmlElement를 제공합니다. string html = hel.OuterHtml; string titmetext = String.Format("김택환입니다.");
int num = html.IndexOf("title", 0); … … html = html.Remove(head, tail); … … html = html.Insert(head, titmetext);
hel.OuterHtml = html; } |
※변경하고자 하는 것의 포커스를 두면 "김택환입니다."으로 title과 alt를 변경합니다.
<title 태그의 속성을 변경한 결과>