이번 시간에는 Naver의 도서검색 OpenAPI를 사용하여 도서명을 입력하면 해당 도서 목록이 나타나는 간단한 도서 검색기 구현에 대한 내용을 다룹니다. 위 그림은 이번 시간에 구현할 최종 어플리케이션으로 전체 소스코드가 필요하신 분은 댓글 이나 메일 주시기 바랍니다.
레이아웃 XAML소스코는 아래와 같습니다.
|
<Grid Background="Black"> <Grid.Resources> <ImageBrush x:Key="ItemBackground" ImageSource="DATABASE_CONTENT.png"/> <Style TargetType="TextBlock" x:Key="ContentText"> <Setter Property="FontSize" Value="12"/> <Setter Property="FontFamily" Value="Myriad Pro" /> <Setter Property="Foreground" Value="White"/> <Setter Property="VerticalAlignment" Value="Center" /> </Style> <Style TargetType="ListBoxItem"> <Setter Property="Opacity" Value="0.5" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Grid Width="600" Height="90" Background="Black" Margin="0,0,0,10"> <Rectangle RadiusX="5" RadiusY="5" Stroke="#3FFFFFFF" StrokeThickness="3"/> <Image Source="{Binding Image}" Width="60" Height="65" Stretch="Fill" HorizontalAlignment="Left" Margin="20,0"/> <Grid Width="500" Height="60" HorizontalAlignment="Right" Margin="0,0,10,0" Cursor="Hand"> <Grid.ColumnDefinitions> <ColumnDefinition Width="70"/> <ColumnDefinition Width="180"/> <ColumnDefinition Width="70"/> <ColumnDefinition Width="180"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="20" /> <RowDefinition Height="20" /> <RowDefinition Height="20" /> </Grid.RowDefinitions> <TextBlock Style="{StaticResource ContentText}" Grid.Column="0" Grid.Row="0" Text="Title"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="1" Grid.Row="0" Text="{Binding Title}"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="2" Grid.Row="0" Text="Author"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="3" Grid.Row="0" Text="{Binding Author}"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="0" Grid.Row="1" Text="Price"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="1" Grid.Row="1" Text="{Binding Price}"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="2" Grid.Row="1" Text="Discount"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="3" Grid.Row="1" Text="{Binding Discount}"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="0" Grid.Row="2" Text="Publisher"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="1" Grid.Row="2" Text="{Binding Publisher}"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="2" Grid.Row="2" Text="ISBN"/> <TextBlock Style="{StaticResource ContentText}" Grid.Column="3" Grid.Row="2" Text="{Binding ISBN}"/> </Grid> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Grid.Resources> <StackPanel> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right"> <TextBlock Style="{StaticResource ContentText}" Text="- Keyword :"/> <TextBox x:Name="TxtKeyword" Width="200" Margin="5,0"/> <Button Content="Search" Click="Button_Click"/> </StackPanel> <ListBox Background="Black" x:Name="LstBook" Height="350" /> </StackPanel> </Grid> |
ListBox를 사용하였고 ListBoxItem의 Style과 ControlTemplate을 수정하여 도서와 관련된 내용이 Binding되도록 정의했습니다. ListBox에 추가할 아이템으로 사용할 수 있도록 아래와 같이 Book이라는 Class를 생성합니다.
|
public class Book { public string Title { get; set; } public string Author { get; set; } public string Price { get; set; } public string Discount { get; set; } public string Publisher { get; set; } public string ISBN { get; set; } public string Image { get; set; } } |
여기까지 하면 이제 도서 검색을 위한 기본적인 틀은 준비가 다 된 것 입니다. 그럼 실제 OpenAPI를 사용해서 데이터를 가져오는 방법에 대해 설명하겠습니다.
OpenAPI는 서비스업체가 제공하는 URL로 특정 Query를 전송하면 해당 Query에 맞는 내용을 XML형태의 데이터를 반환해주는 형태를 띄고 있습니다. 우리는 OpenAPI에서 제공하는 XML형태의 데이터를 사용하기 위해 System.XML Namespace에서 제공하는 XMLDocument라는 Class를 사용하면 쉽게 데이터에 접근할 수 있습니다. 사용 방법은 매우 간단하며 아래와 같이 XmlDocument객체를 생성하고 Load 메서드를 사용하여 불러오기만 하면 됩니다. Load 메서드의 파라미터로는 로컬 컴퓨터에 저장된 파일의 경로나 웹 상의 주소를 사용 할 수 있습니다.
XmlDocument Document = new XmlDocument();
Document.Load("XML Document Path or URL");
이렇게 XML Document를 얻고 실제 우리가 필요로 하는 아이템들을 얻기 위해 우리가 필요한 노드를 선택 할 수 있습니다. XMLDocument 객체의 SelectNodes메서드를 사용합니다. SelectNodes메서드는 해당 Xml Path에 존재하는 Node의 List를 반환합니다.
XmlNodeList BookItems = Document.SelectNodes("rss/channel/item");
Rss/channel/item 은 RSS Node에 포함된 Channel Node에 포함된 Item Node를 가져 오겠다는 의미이며 이제 앞에서 구현한 Layout과 Naver OpenAPI를 사용하여 도서 목록을 가져오는 부분을 구현하면 다음과 같이 구현 할 수 있습니다.
|
public void Search(string Query) { XmlDocument Document = new XmlDocument(); Document.Load("http://openapi.naver.com/search?key=87b0c706f01ebc494df5ea894a6c0aaa&display=10&start=1&target=book&sort=sim&query=" + Query); XmlNodeList BookItems = Document.SelectNodes("rss/channel/item"); LstBook.Items.Clear(); foreach (XmlNode Item in BookItems) { Book BookItem = new Book(); BookItem.Title = Item["title"].InnerText; BookItem.Author = Item["author"].InnerText; BookItem.Discount = Item["discount"].InnerText; BookItem.ISBN = Item["isbn"].InnerText; BookItem.Price = Item["price"].InnerText; BookItem.Publisher = Item["publisher"].InnerText; BookItem.Image = Item["image"].InnerText; LstBook.Items.Add(BookItem); } TxtKeyword.Text = ""; } private void Button_Click(object sender, RoutedEventArgs e) { Search(TxtKeyword.Text); } |
Search 함수를 살펴보면 앞에서 설명했던 방법대로 XmlNodeList를 가져오고 foreach문을 사용해 각각의 Node에 저장된 내용을 가져오는 것을 확인 할 수 있습니다.

