Created
January 19, 2011 18:07
-
-
Save usagi/786566 to your computer and use it in GitHub Desktop.
sample: how to use XPath for JSON easy with .net 4.0 and Google apps search images.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Runtime.Serialization.Json; | |
using System.Xml; | |
using System.Xml.Linq; | |
using System.Xml.XPath; | |
using System.Web; | |
namespace wrp.code_test | |
{ | |
public class google_search_images | |
{ | |
public static IEnumerable<string> invoke(string q) | |
{ | |
var i = new google_search_images(HttpUtility.UrlEncode(q)); | |
return i.invoke(0, new string[] { }); | |
} | |
protected IEnumerable<string> invoke(uint start, IEnumerable<string> r) | |
{ | |
XDocument x; | |
using (var str = new WebClient().OpenRead(url(start))) | |
x = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(str, new XmlDictionaryReaderQuotas())); | |
var z = x.XPathSelectElements(xpath_urls).Select(e => { return e.Value; }); | |
return (x.XPathSelectElement(xpath_response_data).Attribute(xml_attribute_type_name).Value != xml_attribute_type_value_null) | |
? invoke(start + rsz, r.Union(x.XPathSelectElements(xpath_urls).Select(e => { return e.Value; }))) | |
: r; | |
} | |
protected google_search_images(string q) | |
{ url_base = "http://ajax.googleapis.com/ajax/services/search/images?v=" + v + "&hr=" + hr + "&rsz=" + rsz + "&q=" + q; } | |
protected string url(uint start) { return url_base + "&start=" + start; } | |
protected const string xml_attribute_type_name = "type"; | |
protected const string xml_attribute_type_value_null = "null"; | |
protected const string xpath_response_data = "/root/responseData"; | |
protected const string xpath_urls = "/root/responseData/results//url"; | |
protected string q = string.Empty; | |
protected uint start = 0; | |
protected uint rsz = 8; | |
protected string hr = "ja"; | |
protected string v = "1.0"; | |
protected readonly string url_base; | |
} | |
} | |
namespace code_test_dotnet | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
wrp.code_test.google_search_images.invoke("site:usagi.chalou.info") | |
.AsParallel() | |
.ForAll(e => { Console.WriteLine(e); }); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment