我想用它的代码替换html字符串中的JQuery script标记。这意味着将script标记( src属性设置为“script/jQuery1.9.1.js”)移除为包含JQuery当前源代码的script标记。
我使用以下代码创建一个新节点:
HtmlNode node = new HtmlNode(HtmlNodeType.Element, htmlDocument, index);
node.Name = "script";
node.PrependChild(HtmlNode.CreateNode(jQuerySourceCodeString));无论我对jQuerySourceCodeString做了什么,它总是被截断为:
<script>/*!
* jQuery JavaScript Library v1.9.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-2-4
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE</script>这显然不是我们可以找到的这里代码
我做错什么了?
更新:
我不能使用InnerHtml,因为它试图将它作为html来读取。
2-当HtmlNode.CreateNode方法发现这个"<“时,它会崩溃,它认为它是标记的开头,但它不是。
发布于 2016-07-06 14:37:05
考虑到您的问题是如何将一个script节点附加到已解析的html文档中(因为您希望删除现有的脚本节点,从脚本src的uri中检索源,并添加一个带有结果的新节点),我创建了一个示例来重现您想要做的事情。
script节点下。我尝试过用HtmlAgilityPack做一些尝试,但是最终的html总是有一个尾随垃圾,如下所示
</div></10></=></9></=8></"></$1></(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^></(?:"></use></9></table></tfoot></thead></tbody></table></tbody></9></=></"></[\w\w]+></tag></\></([\w-]+)\s*\></number></9></9></1.9.8+></10></=8></script>然后我放弃了,尝试了另一个我经常使用的html解析器-- AngleSharp。通过它,我得到了一个正确的结果html。
以下是两次尝试的代码片段:
HtmlAgilityPack:
string html = @"
<html>
<head><title>SO Question</title></head>
<body>
<div>
text text text
</div>
</body>
<script>
var a = 10;
</script>
</html>
";
var jsCode = File.ReadAllText("D:/jquery-1.12.4.js", Encoding.UTF8);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode jsNode = new HtmlNode(HtmlNodeType.Element, doc, 0);
jsNode.Name = "script";
jsNode.InnerHtml = jsCode;
doc.DocumentNode.InsertAfter(jsNode, doc.DocumentNode.SelectSingleNode("body"));
File.WriteAllText("D:/jsCodeOut.html", doc.DocumentNode.InnerHtml);AngleSharp:
string html = @"
<html>
<head><title>SO Question</title></head>
<body>
<div>
text text text
</div>
</body>
<script>
var a = 10;
</script>
</html>
";
var jsCode = File.ReadAllText("D:/jquery-1.12.4.js", Encoding.UTF8);
HtmlParser hp = new HtmlParser();
var parsedHtml = hp.Parse(html);
var scriptNode = parsedHtml.CreateElement("script");
scriptNode.InnerHtml = jsCode;
parsedHtml.DocumentElement.AppendChild(scriptNode);
File.WriteAllText("D:/angleSharpOutput.html", parsedHtml.DocumentElement.InnerHtml);结论:
如果你只需要用HtmlAgilityPack来做这件事,那么我的帖子最终是毫无帮助的。否则,尝试AngleSharp,您已经解决了您的问题。
发布于 2016-10-14 14:37:14
使用HtmlAgilityPack,您可以使用textNode:
jsNode.AppendChild(doc.CreateTextNode(jsCode));https://stackoverflow.com/questions/38210294
复制相似问题