How to Use the Wikipedia API to Get Images
Wikipedia includes an application programming interface for .NET, so you can use the data from the website in your own websites. The API returns data for a specified article in the XML format, so you must parse the XML in your code. The Microsoft .NET language includes libraries that parse the XML data returned from any API. You connect to the API URL, retrieve to the XML and use the "imageinfo" node to get the image.
Instructions
-
-
1
Open Visual Studio and open the project in which you want to use the Wikipedia API. Double-click the code file you want to use to retrieve the image.
-
2
Add the XML libraries to the file. Copy and paste the following code to the top of your source code file:
using System.Xml;
using System.Xml.XPath; -
-
3
Connect to the API. The .NET WebRequest class connects to a URL and retrieves the response. Use the following code to connect to the Wikipedia API:
HttpWebRequest req = (HttpWebRequest)req.Create("http://en.wikipedia/wiki/Special:Export/article_name");
req.Credentials = System.Net.CredentialCache.DefaultCredentials;
req.Accept = "text/xml";Replace "article_name" with the name of the article you want to retrieve.
-
4
Load the response from the API into an XML stream reader. The stream reader automatically parses the XML, so you just need to reference the image node to get its content. Add the following code after the WebRequest code:
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Stream read= res.GetResponseStream();
XmlReader reader= new XmlTextReader(read);
String NS = "http://www.mediawiki.org/xml/export-0.3/";
XPathDocument doc = new XPathDocument(reader);
reader.Close();
res.Close();
XPathNavigator nav= doc.CreateNavigator();
XPathNodeIterator nodesIt = myXPathNavigator.SelectDescendants("imageinfo", NS, false); -
5
Display the image information. The image information is stored in the "nodeslt" variable. The following code displays the image:
Response.Write (odesIt.Current.InnerXml);
-
1