通过 id 获取 div 个内容
Get div content by id
我有一个字符串可以保存整个 html 文档。我想获取具有特定 ID 的 div 中的所有内容。例如:
<div id="myId" class = "myClass">
<div class = "myClass">hello</div>
</div>
我需要 id="myId" 标签和结束标签之间的内容。
有什么办法可以做到这一点?输出应该是第二行。
你想要 server side
处的 c#
代码中的任何 div
中的 html
,所以你可以这样做。
<div id="myId" class = "myClass" runat="server">
<div class = "myClass">hello</div>
</div>
因此您必须将 runat="server"
属性添加到 div 才能访问服务器 C#
代码中的 div。
并像这样访问:
Debug.WriteLine(myId.InnerHtml);
并检查 output
window 你会得到 <div class = "myClass">hello</div>
这个。
快乐编码
干净而正确的方法是通过 HTML 解析器,例如 HtmlAgilityPack:
string stringThatKeepsYourHtml = "<div id=....";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(stringThatKeepsYourHtml);
string whatUrLookingFor = doc.GetElementbyId("myId").InnerHtml;
第 1 步。将 HTML 元素设为 runat = 'server' 并提供 ID。
<div id="myId" class = "myClass" runat="server">
<div class = "myClass">hello</div>
</div>
第 2 步。使用下面的 C# 代码获取 Div HTML 字符串。
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 是您的 DIV ID。
- 或者您可以使用 HTML 敏捷包 (HAP)
我有一个字符串可以保存整个 html 文档。我想获取具有特定 ID 的 div 中的所有内容。例如:
<div id="myId" class = "myClass">
<div class = "myClass">hello</div>
</div>
我需要 id="myId" 标签和结束标签之间的内容。 有什么办法可以做到这一点?输出应该是第二行。
你想要 server side
处的 c#
代码中的任何 div
中的 html
,所以你可以这样做。
<div id="myId" class = "myClass" runat="server">
<div class = "myClass">hello</div>
</div>
因此您必须将 runat="server"
属性添加到 div 才能访问服务器 C#
代码中的 div。
并像这样访问:
Debug.WriteLine(myId.InnerHtml);
并检查 output
window 你会得到 <div class = "myClass">hello</div>
这个。
快乐编码
干净而正确的方法是通过 HTML 解析器,例如 HtmlAgilityPack:
string stringThatKeepsYourHtml = "<div id=....";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(stringThatKeepsYourHtml);
string whatUrLookingFor = doc.GetElementbyId("myId").InnerHtml;
第 1 步。将 HTML 元素设为 runat = 'server' 并提供 ID。
<div id="myId" class = "myClass" runat="server">
<div class = "myClass">hello</div>
</div>
第 2 步。使用下面的 C# 代码获取 Div HTML 字符串。
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 是您的 DIV ID。
- 或者您可以使用 HTML 敏捷包 (HAP)