This project has moved. For the latest updates, please go here.

Wrap all nodes in a parent p

Topics: Developer Forum
Jul 22, 2011 at 2:15 PM
Edited Jul 22, 2011 at 3:05 PM

I have a string of text which can contain many nodes like paragraphs headers and pictures.

The first node may or may not be a paragraph. e.g





I want to ensure all my text is wrapped in a p tag so the above would become






However I only want to add the surrounding tags if they do not already exist.

I somehow need to select all text that is not already in a node and wrap it in paragraphg tags?

  public string WrapParagraph(string input)
            HtmlDocument doc = new HtmlDocument();
            String parsedtext;
            HtmlNode n = doc.DocumentNode.ParentNode;
            if (n != null && n.ParentNode.Name !="//p")
                n.InsertBefore(HtmlNode.CreateNode("<p>"), n);
            return parsedtext = doc.DocumentNode.InnerHtml.ToString();