Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get div content by id

I have a string that keeps entire html document. I would like to get all the content inside a div with specific id. For example:

<div id="myId" class = "myClass">
 <div class = "myClass">hello</div>
</div>

I need the content between the tag with id="myId" and it's closing tag. Any way to achieve this? The output should be the second line.

like image 703
Ofer Gozlan Avatar asked Dec 04 '22 01:12

Ofer Gozlan


2 Answers

The clean and correct way would be via an HTML parser, like HtmlAgilityPack:

string stringThatKeepsYourHtml = "<div id=....";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(stringThatKeepsYourHtml);
string whatUrLookingFor = doc.GetElementbyId("myId").InnerHtml;
like image 121
Saeb Amini Avatar answered Dec 18 '22 14:12

Saeb Amini


You want the html of inside the any div in c# code at the server side so you can do like this.

<div id="myId" class = "myClass" runat="server">
 <div class = "myClass">hello</div>
</div>

so you must be add the runat="server" attribute to that div to access that div on the C# code on the server.

and access like this:

Debug.WriteLine(myId.InnerHtml);

And check the output window you will get the <div class = "myClass">hello</div> this.

Happy Coding

like image 28
Kalpesh Rajai Avatar answered Dec 18 '22 14:12

Kalpesh Rajai