问题
If you see the following code
Table tblTest = (Table)tblControl;
StringBuilder text = new StringBuilder();
StringWriter writer = new StringWriter(text);
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
tblTest.RenderControl(htmlWriter);
htmlCode = text.ToString();
here i am converting a table object to string.
I'll get the output as "<table><tr><td>item</td></tr></table>"
Now i want to Rollback it. I am having a string and i need to convert that into WebControls.Table object. Please someone suggest some way.
回答1:
Create a map of the name an HtmlControl is rendered with to the control. Then you can take the xml string sent to you and load it using XDocument.Parse. From there you can recursively build the control structure.
Dictionary<string, HtmlContainerControl> controlConstructor = new Dictionary<string, HtmlContainerControl>
{
{"table", new HtmlTable()},
{"tr", new HtmlTableRow()},
{"td", new HtmlTableCell()}
};
string xml = "<table><tr><td>item</td></tr></table>";
var htmlDoc = XElement.Parse(xml);
Func<XElement, HtmlControl> constructHtmlStructure = null;
constructHtmlStructure = e =>
{
var control = controlConstructor[e.Name.ToString()];
if (e.HasElements)
control.Controls.Add(constructHtmlStructure(e.Elements().Single()));
else
control.InnerText = e.Value;
return control;
};
var structure = constructHtmlStructure(htmlDoc);
Is a very simple start. You'll need something much more complicated to get all controls. Note that they have a TagName property which you can use to capture all controls in building your dictionary.
来源:https://stackoverflow.com/questions/7013733/convert-string-to-webcontrols-asp-net