简体   繁体   English

ASP.NET将原始HTML解析为控件

[英]ASP.NET Parsing raw HTML into Controls

Is it possible in ASP.NET to take a string containing some HTML and make ASP.NET to parse it and create a Control for me? 在ASP.NET中是否可以获取包含一些HTML的字符串并使ASP.NET解析它并为我创建一个Control? For example: 例如:

string rawHTML = "<table><td><td>Cell</td></tr></table>";
HTMLTable table = MagicClass.ParseTable(rawHTML);

I know that this is a bad thing to do but I am in the unfortunate situation that this is really the only way I can achieve what I need (as I cannot modify this particular coworker's code). 我知道这是一件坏事,但我处于不幸的境地,这是我能够实现我所需要的唯一方式(因为我不能修改这个特定的同事的代码)。

Also, I know that LiteralControl allows you to have a control with arbitrary HTML in it, but unfortunately I need to have them converted to proper control. 另外,我知道LiteralControl允许你在其中控制任意HTML,但不幸的是我需要将它们转换为适当的控制。

Unfortunately, HTMLTable does not support the InnerHTML property. 不幸的是,HTMLTable不支持InnerHTML属性。 I need to preserve the HTML tree exactly as it is, so I cannot put it into a <div> tag. 我需要完全保留HTML树,所以我不能把它放到<div>标签中。

Thanks. 谢谢。

The closest I think you'll get is Page.ParseControl , which is the ASP.NET parser. 我认为你最接近的是Page.ParseControl ,它是ASP.NET解析器。 The downside is that the text you have is a LiteralControl, since it doesn't have runat="server" on it - so you 'll do a very tiny bit of string manipulation beforehand. 缺点是你拥有的文本 LiteralControl,因为它上面没有runat =“server” - 所以你事先会做一点点的字符串操作。

In otherwords: 换一种说法:

this.ParseControl("<table><tr><td>Cell</td></tr></table>")

will produce: 将产生:

Control
 LiteralControl

whereas: 然而:

this.ParseControl("<table runat=\"server\"><tr><td>Cell</td></tr></table>")

will produce: 将产生:

Control
 HtmlTable
  HtmlTableRow
   HtmlTableCell
    LiteralControl

You could traverse the HTML string a token at a time (token defined here as HTML Element or HTML InnerText), and determine which control needs to be instantiated, and what attributes it needs. 您可以一次遍历HTML字符串一个标记(此处将标记定义为HTML元素或HTML InnerText),并确定需要实例化哪个控件,以及它需要哪些属性。 But, that would be something highly... evil in the writing. 但是,这将是一个高度......写作中的邪恶。

Why exactly do you need it to be a "proper" control as opposed to a text inside of a Literal control? 为什么你需要它才能成为一个“正确的”控件而不是Literal控件中的文本?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM