问题
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