Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Htmlagilitypack: create html text node

In HtmlAgilityPack, I want to create HtmlTextNode, which is a HtmlNode (inherts from HtmlNode) that has a custom InnerText.

HtmlTextNode CreateHtmlTextNode(string name, string text)
{
     HtmlDocument doc = new HtmlDocument();
     HtmlTextNode textNode = doc.CreateTextNode(text);
     textNode.Name = name;
     return textNode;
}

The problem is that the textNode.OuterHtml and textNode.InnerHtml will be equal to "text" after the method above.

e.g. CreateHtmlTextNode("title", "blabla") will generate: textNode.OuterHtml = "blabla" instead of <Title>blabla</Title>

Is there any better way to create HtmlTextNode?

like image 999
Nizar Blond Avatar asked Jan 02 '14 12:01

Nizar Blond


2 Answers

The following lines creates a outer html with content

var doc = new HtmlDocument();

// create html document
var html = HtmlNode.CreateNode("<html><head></head><body></body></html>");
doc.DocumentNode.AppendChild(html);

// select the <head>
var head = doc.DocumentNode.SelectSingleNode("/html/head");

// create a <title> element
var title = HtmlNode.CreateNode("<title>Hello world</title>");

// append <title> to <head>
head.AppendChild(title);

// returns Hello world!
var inner = title.InnerHtml;

// returns <title>Hello world!</title>
var outer = title.OuterHtml;

Hope it helps.

like image 159
csteinmueller Avatar answered Oct 15 '22 15:10

csteinmueller


A HTMLTextNode contains just Text, no tags.

It's like the following:

<div>                                   - HTML Node
    <span>text</span>                   - HTML Node
    This is the Text Node               - Text Node
    <span>text</span>                   - HTML Node
</div>

You're looking for a standard HtmlNode.

HtmlDocument doc = new HtmlDocument();
HtmlNode textNode = doc.CreateElement("title");
textNode.InnerHtml = HtmlDocument.HtmlEncode(text);

Be sure to call HtmlDocument.HtmlEncode() on the text you're adding. That ensures that special characters are properly encoded.

like image 38
jessehouwing Avatar answered Oct 15 '22 16:10

jessehouwing