Wrap all nodes in a parent p

Topics: Developer Forum
Jul 22, 2011 at 3:15 PM
Edited Jul 22, 2011 at 4: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

<p>fhfhjvhvhlvhjv</p>

fchcjcjlcl

<h1>hjchjc</h1>

 

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

<p>

<p>fhfhjvhvhlvhjv</p>

<p>fchcjcjlcl</p>

<h1>hjchjc</h1>

</p>

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();
            doc.LoadHtml(input);
            String parsedtext;
            HtmlNode n = doc.DocumentNode.ParentNode;
            if (n != null && n.ParentNode.Name !="//p")
            {
                n.InsertBefore(HtmlNode.CreateNode("<p>"), n);
                doc.DocumentNode.WriteTo();
            }
            return parsedtext = doc.DocumentNode.InnerHtml.ToString();

        }