My javascript is being messed up by HTML Agility Pack.

html-agility-pack javascript

Question

I'm outputting some javascript in the document's head using the HTML Agility Pack. However, I discovered that the javascript code had been altered after saving the document to the file system. I suppose HAP is attempting to verify my script since this is happening. Is there a way to stop this? As you can see below, I've already experimented with several settings.

My HAP code is:

var htmlDoc = new HtmlDocument();
htmlDoc.OptionCheckSyntax = false;
htmlDoc.OptionAutoCloseOnEnd = false;
htmlDoc.OptionFixNestedTags = false;
htmlDoc.LoadHtml(htmlContent);

HtmlNode headNode = htmlDoc.DocumentNode.SelectSingleNode("//head");
headNode.AddScriptNode(htmlDoc, "../../Scripts/jquery-1.7.1.min.js");

Adding the script tag using the extension method

public static void AddScriptNode(this HtmlNode headNode, HtmlDocument htmlDoc, string filePath)
{
    string content = "";

    using (StreamReader rdr = File.OpenText(filePath))
    {
        content = rdr.ReadToEnd();
    }
    if(headNode != null)
    {
        HtmlNode scripts = htmlDoc.CreateElement("script");
        scripts.Attributes.Add("type", "text/javascript");
        scripts.InnerHtml = "\n" + content + "\n";
        headNode.AppendChild(scripts);
    }
}
1
3
2/27/2012 1:42:25 PM

Accepted Answer

My theory is that while utilizingscripts.InnerHtml AgilityPack makes an attempt to convert the text to HTML. As a result, any tags present there will be transformed into HTML nodes.

You should adjust the content of the to prevent this.<script> like text. Unfortunately,HtmlNode.InnerText There is a solution for the read-only property. You may simply add a text node (a remark node is preferred) to your<script> node:

if(headNode != null)
{
    HtmlNode scripts = htmlDoc.CreateElement("script");
    scripts.Attributes.Add("type", "text/javascript");
    scripts.AppendChild(htmlDoc.CreateComment("\n" + content + "\n"));
    headNode.AppendChild(scripts);
}

Your script's body will be put here as a comment node (<!-- and --> being added).

9
2/27/2012 4:48:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow