0

I have the following JQUERY code that relates to a html document from a website.

$

Anything is appreciated,

Salute.

2
  • 2
    You will need a lib to parse the html string like HtmlAgilityPack Commented Dec 18, 2014 at 21:11
  • jQuery and c# are not interchangeable, so there isn't a direct translation from the javascript you write for your jQuery, to c#. Do you mean that you are trying to generate the javascript in your example by using c#? Commented Dec 18, 2014 at 21:31

2 Answers 2

1

From what I can remember using the HtmlAgilityPack

var rawText = "<html><head><head><body><div id='container'><article><p>stuff<p></article><article><p>stuff2</p></article></div></body></html>";

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(rawText);

var stuff = doc.DocumentNode.Descendants("div")
    .SelectMany(div => div.Descendants("article"));
var length = stuff.Count();
var textValues = stuff.Select(a => a.InnerHtml).ToList();

Output: length: 2

textValues: List<String> (2 items) <p>stuff<p> <p>stuff2</p>

To get the HTML, instead of hardcoding it as above, use the WebClient class since it has a simplier API than WebRequest.

var client = new WebClient();
var html = client.DownloadString("http://yoursite.com/file.html");
Sign up to request clarification or add additional context in comments.

Comments

0

To answer your question specifically related to using the System.Net namespace you would do this:

  1. go here to see the way to use the WebRequest class itself to get the content.

    http://msdn.microsoft.com/en-us/library/456dfw4f%28v=vs.110%29.aspx

  2. Next after you get the content back you need to parse it using HTMLAgility pack found here: http://htmlagilitypack.codeplex.com/

How would one code the JQUERY into C#, this is an untested example:

var doc = new HtmlDocument();  
doc.Load(@"D:\test.html");  //you can also use a memory stream instead.
var  container = doc.GetElementbyId("continer");
foreach (HtmlNode node in container.Elements("img"))
{
    HtmlAttribute valueAttribute = node.Attributes["value"];
    if (valueAttribute != null) Console.WriteLine(valueAttribute.Value);

}

In your case the attributes you want after you find the element are alt, src, and href

It will take you about 1 day to learn agilitypack but it's mature fast and well liked by the community.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.