2014-06-17 2 views
1

wikipedia api 페이지의 콘텐츠를 다운로드하고 페이지의 문자를 대체하여 텍스트 상자에 표시하고 싶습니다.C에서 텍스트 상자에 위키 피 디아 콘텐츠를 얻는 방법

예 : 링크 페이지

http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=1&titles=stack%20overflow

에 나는

{"query":{"normalized":[{"from":"stack overflow","to":"Stack overflow"}],"pages":{"1436888":{"pageid":1436888,"ns":0,"title":"Stack overflow","extract": 

같은 모든 원치 않는 물건을 교체해야합니다.

나는이 시도했습니다하지만 그것은 당신이 얻을하지만 JSON 더하여 XDocument/XML 없다 페이지

textbox1.Text = XDocument.Parse(new Regex("[[(.*?]]").Matches(new WebClient().DownloadString("http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=1&titles=stack%20overflow")[0].Value).Root.Value; 

답변

1

텍스트를 얻는 가장 좋은 방법은 JSON을 사용하여 응답을 deserialize하는 것입니다. 다음은 Newtonsoft JSON 구문 분석기를 사용한 예입니다. 전체 응답에 관심이 없으므로 노드 이름 "추출"로 이동하는 데 필요한 부분을 비 직렬화하면됩니다. https://dotnetfiddle.net/xGv7lG

: 여기
using System; 
using System.Collections.Generic; 
using System.Net; 
using System.IO; 
using System.Linq; 
using Newtonsoft.Json; 

public class Program 
{ 
    public static void Main() 
    { 
     WebClient client = new WebClient(); 

     using (Stream stream = client.OpenRead("http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=1&titles=stack%20overflow")) 
     using (StreamReader reader = new StreamReader(stream)) 
     { 
      JsonSerializer ser = new JsonSerializer(); 
      Result result = ser.Deserialize<Result>(new JsonTextReader(reader)); 

      foreach(Page page in result.query.pages.Values) 
       Console.WriteLine(page.extract); 
     } 
    } 
} 

public class Result 
{ 
    public Query query { get; set; } 
} 

public class Query 
{ 
    public Dictionary<string, Page> pages { get; set; } 
} 

public class Page 
{ 
    public string extract { get; set; } 
} 

는 코드 작업의 바이올린입니다
0

작동하지. 당신이 그런 다음의 콘텐츠에 액세스 할 수 있습니다

var deserialized = JsonConvert.DeserializeObject<YourJsonRootClass>(rawJsonString); 

을 할 수 http://json2csharp.com/

이 Newtonsoft JSON 그래서

의 NuGet 패키지를 다운로드 :

당신은 여기 JSON에 대한 C# 클래스를 만들 수 있습니다 페이지를 "역 직렬화 된 객체"에 추가하십시오.

또는 JSON을 동적으로 구문 분석 할 수도 있지만 여기서 여기서는 설명하지 않겠습니다.

관련 문제