我有一个客户端生成的HTML行(<tr>
),我想转换包含HtmlTableRow
控件中的行单元格信息的字符串。这是我迄今为止使用Convert string to WebControls - asp.net上的示例完成的。由于将字符串转换为HtmlTableRow控件
string row = "<tr><td>item</td><td><input name=\"radio0\" type=\"radio\"/></td></tr>";
Dictionary<string, HtmlContainerControl> controlConstructor = new Dictionary<string, HtmlContainerControl>
{
{"tr", new HtmlTableRow()},
{"td", new HtmlTableCell()}
};
var htmlDoc = XElement.Parse(row);
Func<XElement, HtmlControl> constructHtmlStructure = null;
constructHtmlStructure = (o =>
{
var control = controlConstructor[o.Name.ToString()];
if (o.HasElements)
{
control.Controls.Add(constructHtmlStructure(o.Elements().Single())); //Exception: Sequence contains more than one element (When is a input item)
}
else
{
control.InnerText = o.Value;
}
return control;
});
HtmlTableRow structure = (HtmlTableRow)constructHtmlStructure(htmlDoc);
感谢您的评论!但是..它不起作用structure.Cells.Count只返回1它可能是2 – christiangobo 2013-03-02 21:30:56
不知道我跟着你 - 如果抛出异常,你如何调用'structure.Cells.Count'?你问题中的HTML是一个包含两个'td'的'tr';所以第一次执行'constructHtmlStructure','o'('tr')'.Elements()'('td's)将返回两个元素。这就是为什么'Single()'抛出它所做的错误。 – 2013-03-02 22:33:27
我做了你提出的改变和structure.Cells.Count返回1时,在字符串中的每个是1个单元 – christiangobo 2013-03-02 22:57:41