// 기본적으로 제공되는 dll 외에 추가해야 할 부분들
using System.IO;
using System.Xml;
using System.Xml.XPath;
using SlothLib.Web.Search;
// Form 부분 코드는 생략하였다.
private void ResultBoss (string QueryString, string Count)
{
// 검색결과를 저장할 개체 차용 - YahooJpWebElement 개체를 빌려온다.
// 사실 class를 다시 정해도 되겠지만... SlothLib의 효용성을 극대화한다는 차원에서...
List
// Yahoo! BOSS 질의형식을 충분히 따라서 간다.
string tQuery = "http://boss.yahooapis.com/ysearch/web/v1/"+ QueryString.Trim() + "?format=xml&count=" + Count + "&appid=받은 API Key";
// 검색결과를 획득하는 부분
// HttpWebRequest로 치환한 것을 볼 수 있는데, Http에 대한 사용의 경우는
// 이 개체를 사용하는 것이 더욱 효율적이라고 한다.
// 실제로 반환하는 검색결과의 개수가 많을 수록 효율적임을 체감했다.
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(tQuery);
// 밀리초 기준의 Timeout 개체를 이용해서 자동질의의 딜레이를 처리해 주기도 한다.
// myRequest.Timeout = 5000;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream myStream = myResponse.GetResponseStream();
// 이제 받아온 검색결과를 XML 형태로 변환한다. 선언하고 집어넣으면 끝.
// 특히 Close()를 빼먹으면 퍼포먼스에 심대한 영향을 미친다.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(myStream);
myStream.Close();
myResponse.Close();
// 여기서부터는 Yahoo! BOSS의 XML 형식 응답의 구조를 파악하여 적용한 내용이므로
// 응답형식 자체가 바뀌거나 다른 API를 사용하는 경우는 추가 연구가 필요하다.
// 먼저 루트요소를 획득한다.
XmlElement xmlRoot = xmlDoc.DocumentElement;
// 검색 결과수 추출 및 저장
// API 해설에 보면 totalhits와 deephits가 있는데, 경험적으로 우리가 보는 결과수는
// totalhits로 보인다. 노드에서 attribute 값을 끌어내는 데 표준적인 형태.
XmlNodeList xHitPath = xmlRoot.GetElementsByTagName("resultset_web");
foreach (XmlElement xe in xHitPath)
{
Hit = xe.GetAttribute("totalhits");
}
// 검색 결과 추출 및 저장
// XML Node를 검색할 때 기준이 되는 NodeList를 바꾸어 준다.
XmlNodeList xmlResultList = xmlRoot.GetElementsByTagName("result");
int rank = 0;
// GetElementString() 함수는 맨 아래 정의되어 있으므로 참조 바람.
// 가급적 Yahoo! Japan 검색 결과와 맞추는 데 중점을 두었다.
// 필요한 대로 개체를 치환하여 사용하면 되겠다.
// node의 값과 attribute 값을 가져오는 부분의 차이를 눈여겨 보시길...
foreach (XmlElement xmlResult in xmlResultList)
{
rank++;
string title = GetElementString(xmlResult.GetElementsByTagName("title"));
string summary = GetElementString(xmlResult.GetElementsByTagName("abstract"));
string url = GetElementString(xmlResult.GetElementsByTagName("url"));
string date = string.Empty;
string clickurl = GetElementString(xmlResult.GetElementsByTagName("ClickUrl"));
string mimetype = string.Empty;
string cacheUrl = string.Empty;
string cacheSize = string.Empty;
// 인터페이스로 구성되어 있는 YahooJpWebElement에 이 순위의 값들을 집어넣는다.
YahooJpWebElement result = new YahooJpWebElement(rank, title, summary, url, clickurl, mimetype, date, cacheUrl, cacheSize);
// 사전 정의한 결과값의 list 개체에 잘 저장해 준다.
ResultElementList.Add(result);
}
}
private string GetElementString(XmlNodeList nodeList)
{
if (nodeList.Count == 0)
return string.Empty;
else
return nodeList[0].InnerText;
}
원래 있었던 try - catch 문은 어디로 갔을까?^^
이 부분을 넣지 않으면 XmlException에 대한 처리가 되지 않아 실행이 되지 않는다.
이곳에서는 설명을 보시고 꼭 원래의 코드로 실행해 보시길 부탁드린다.
예전에는 이런 자료를 많이 올리셨었네요?
ReplyDelete원래 고국에 있는 후배들에게 참고하라는 차원에서 시작했던 블로그였지요.
ReplyDelete지금은 취미활동이 주를 이루게 되었지만, 언젠가 다시 시작할 생각입니다^^
멀리까지, 깊게 봐 주시니 감사할 따름이군요.