代码之家  ›  专栏  ›  技术社区  ›  Kraang Prime

C#WebBrowser.Document.Body.AppendChild未能添加新元素

  •  0
  • Kraang Prime  · 技术社区  · 7 年前

    AppendChild 方法需要类型 HtmlElement . 在下面的代码中,我试图克服这个问题 Document.Body 返回类型 HtmlElement公司 所以我创建了一个新的WebBrowser控件,将整个主体设置为文本,然后检索结果 HtmlElement公司 .

    public class WebBrowserEx : WebBrowser {
    
        // method to allow creation of HtmlElement from HTML text
        public HtmlElement CreateElement(string html)
        {
            HtmlElement el;
            using(WebBrowser wb = new WebBrowser())
            {
                wb.Navigate("about:blank");
                try
                {
                    if (wb.Document != null) { wb.Document.Write(string.Empty); }
                } catch (InvalidCastException) { }
                wb.Document.Write(html);
                el = wb.Document.Body;
            }
            return el;
        }
    
        // method to set entire document from HTML text
        public string Html {
            get {
                return DocumentText;
            }
            set{
                Navigate("about:blank");
                try
                {
                    if (Document != null) { Document.Write(string.Empty); }
                } catch (InvalidCastException) { }
                wb.Document.Write(html);
            }
        }
    }
    

    示例使用

    using System;
    using System.Windows.Forms;
    
    public partial class Form1 : Form {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_Load( object sender, EventArgs e )
        {
            // create a new instance of the WebBrowserEx control
            WebBrowserEx wbex = new WebBrowserEx();
    
            // set the document to HTML content
            wbex.Html = "<html><head></head><body></body></html>";
    
            // create a new element from HTML as string
            HtmlElement el = wbex.CreateElement("<h1>Hello World</h1><br>");
    
            // append new element to document
            wbex.Document.Body.AppendChild(el);
        }
    }
    

    我遇到的问题是当我试图使用 Document.Body.AppendChild ,它给了我以下例外:

    值不在预期范围内。

    当尝试使用

    wbex.Document.Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, el);
    

    异常图像

    the exception

    注意

    我知道使用 Document.CreateElement("A")

    目标是能够简单地将html块从字符串添加到已直接加载到WebBrowser控件中的现有html文档中的任何位置。

    0 回复  |  直到 7 年前
    推荐文章