开发者

How can I save HtmlDocument to memory? Html Agility Pack

开发者 https://www.devze.com 2023-03-16 05:21 出处:网络
I am using HTML Agility Pack to parse and HTML document, make a change to a node, and then save the HTML document. I would like to save the document to memory so I can write the 开发者_运维问答HTML ou

I am using HTML Agility Pack to parse and HTML document, make a change to a node, and then save the HTML document. I would like to save the document to memory so I can write the 开发者_运维问答HTML out as a string later in the application. My current implementation always returns a string == "". I can see that the HtmlDocument object is not empty when debugging. Can someone provide some insight?

private string InitializeHtml(HtmlDocument htmlDocument)
    {
        string currentUserName = User.Identity.Name;
        HtmlNode scriptTag = htmlDocument.DocumentNode.SelectSingleNode("//script[@id ='HwInitialize']");
        scriptTag.InnerHtml = 
            string.Format("org.myorg.application = {{}}; org.myorg.application.init ={{uid:\"{0}\", application:\"testPortal\"}};",currentUserName);

        MemoryStream memoryStream = new MemoryStream();
        htmlDocument.Save(memoryStream);
        StreamReader streamReader = new StreamReader(memoryStream);
        return streamReader.ReadToEnd();
    }


Try

memoryStream.Seek(0, System.IO.SeekOrigin.Begin)

Before creating the StreamReader and calling ReadToEnd()

The stream pointer is likely getting left at the end of the stream by the Save method (it's best practise for a component to do this - in case you want to append more data to the stream) therefore when you call ReadToEnd, it's already at the end and nothing gets read.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号