Get div content by id

ε祈祈猫儿з 提交于 2019-12-23 15:28:45

问题


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.


回答1:


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;



回答2:


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




回答3:


Step 1. Make HTML element to runat = 'server' and give ID.

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

Step 2. Use below C# code to get Div HTML string.

System.IO.StringWriter sw = new System.IO.StringWriter();
       System.Web.UI.HtmlTextWriter h = new System.Web.UI.HtmlTextWriter(sw);
                myId.RenderControl(h);
                string str = sw.GetStringBuilder().ToString();
  • myId is your DIV Id.
  • Or you can use HTML Agility Pack(HAP)


来源:https://stackoverflow.com/questions/36689095/get-div-content-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!