从一个完整的html字符串构建HtmlGenericControl
本文关键字:html 字符串 构建 HtmlGenericControl 一个 | 更新日期: 2023-09-27 18:08:31
我希望能够将属性添加到html字符串,而无需构建解析器来处理html。在一个特定的情况下,我希望能够提取html的id或将id插入到html服务器端。
假设我有:
string stringofhtml = "<img src='"someimage.png'" alt='"the image'" />";
我希望能做这样的事情:
HtmlGenericControl htmlcontrol = new HtmlGenericControl(stringofhtml);
htmlcontrol.Attributes["id'] = "newid";
或
int theid = htmlcontrol.Attributes["id"];
这只是一种方式,我可以访问/添加属性的html字符串,我有
你可以这样做:
HtmlGenericControl ctrl = new HtmlGenericControl();
ctrl.InnerHtml = "<img src='"someimage.png'" alt='"the image'" />";
你也可以使用LiteralControl,而不是HtmlGenericControl:
LiteralControl lit = new LiteralControl(stringOfHtml);
我不认为有一个可用的控件可以为您提供您正在寻找的功能。
下面我使用了htmllagility包来解析/查询HTML,并创建了一个新的控件子类Literal控件。
该控件接受一个HTML字符串,检查它是否至少包含一个元素,并提供获取/设置该元素属性的访问权限。
string image = "<img src='"someimage.png'" alt='"the image'" />";
HtmlControlFromString htmlControlFromString = new HtmlControlFromString(image);
htmlControlFromString.Attributes["id"] = "image2";
string id = htmlControlFromString.Attributes["id"];
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
public class HtmlControlFromString : Literal
{
private HtmlDocument _document = new HtmlDocument();
private HtmlNode _htmlElement;
public AttributesCollection Attributes { get; set; }
public HtmlControlFromString(string html)
{
_document.LoadHtml(html);
if (_document.DocumentNode.ChildNodes.Count > 0)
{
_htmlElement = _document.DocumentNode.ChildNodes[0];
Attributes = new AttributesCollection(_htmlElement);
Attributes.AttributeChanged += new EventHandler(Attributes_AttributeChanged);
SetHtml();
}
else
{
throw new InvalidOperationException("Argument does not contain a valid html element.");
}
}
void Attributes_AttributeChanged(object sender, EventArgs e)
{
SetHtml();
}
void SetHtml()
{
Text = _htmlElement.OuterHtml;
}
}
public class AttributesCollection
{
public event EventHandler AttributeChanged;
private HtmlNode _htmlElement;
public string this[string attribute]
{
get
{
HtmlAttribute htmlAttribute = _htmlElement.Attributes[attribute];
return htmlAttribute == null ? null : htmlAttribute.Value;
}
set
{
HtmlAttribute htmlAttribute = _htmlElement.Attributes[attribute];
if (htmlAttribute == null)
{
htmlAttribute = _htmlElement.OwnerDocument.CreateAttribute(attribute);
htmlAttribute.Value = value;
_htmlElement.Attributes.Add(htmlAttribute);
}
else
{
htmlAttribute.Value = value;
}
EventHandler attributeChangedHandler = AttributeChanged;
if (attributeChangedHandler != null)
attributeChangedHandler(this, new EventArgs());
}
}
public AttributesCollection(HtmlNode htmlElement)
{
_htmlElement = htmlElement;
}
}