[英]Inserting new node in html document in c#
I am trying to insert new node in the document using htmlagilitypack. 我正在尝试使用htmlagilitypack在文档中插入新节点。 I am reading the document from the stream , insert the node and then return the document as a FileContentResult object : 我正在从流中读取文档,插入节点,然后将文档作为FileContentResult对象返回:
HtmlDocument ndoc = new HtmlDocument();
ndoc.Load(stream);
HtmlNode usern = HtmlNode.CreateNode("<img .... />");
usern.Attributes.Add("onclick", "javascript:document.location.href='/Home/Index';");
ndoc.DocumentNode.SelectSingleNode("id('main')").AppendChild(usern);
using (MemoryStream ms = new MemoryStream())
{
ndoc.Save(ms);
ms.Seek(0, System.IO.SeekOrigin.Begin);
fileBytes = ms.ToArray();
}
FileContentResult file = File(fileBytes, "text/html");
return file;
Problem : New node ( img ) is not inserting. 问题:未插入新节点(img)。 My footer content gone if i am using this code and if i just read the document from the stream and return as a FileContentResult then everything perfect. 如果我使用此代码,并且如果我只是从流中读取文档并作为FileContentResult返回,那么我的页脚内容就不存在了,那么一切就完美了。 I want to know whats the problem with this code or where i am doing wrong ? 我想知道这段代码是什么问题,或者我在哪里做错了?
Take a look at HTML Agility pack create new HTMLNode . 看一下HTML Agility包,创建新的HTMLNode 。
This shows how to properly create a new node. 这显示了如何正确创建新节点。 In my experience, their code works fine. 以我的经验,它们的代码可以正常工作。 Similar to jQuery taking it step by step. 与jQuery逐步相似。 Good luck! 祝好运!
try to change 尝试改变
HtmlNode usern = HtmlNode.CreateNode("<img .... />");
to just img 只是img
HtmlNode usern = HtmlNode.CreateNode("<img></img>");
and add this 并添加此
ndoc.OptionWriteEmptyNodes = true;
I came across the same issue, resolved it by passing the clone object. 我碰到了同样的问题,通过将克隆对象解决它。 just modify the line 只需修改行
ndoc.DocumentNode.SelectSingleNode("id('main')").AppendChild(usern);
to 至
ndoc.DocumentNode.SelectSingleNode("id('main')").AppendChild(usern.CloneNode(true));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.