【问题标题】:Manualy created HtmlDocument.DocumentNode returns null from InnerHtml手动创建的 HtmlDocument.DocumentNode 从 InnerHtml 返回 null
【发布时间】:2020-05-19 16:41:38
【问题描述】:

尝试从代码手动构建 HTML。构建html的代码:

            public string ParseFromRoot(RootItem root)
            {
                if (root == null || root.Children.Count == 0)
                    return string.Empty;

                var document = new HtmlDocument();

                foreach (var item in root.Children)
                    ParseNode(document, document.DocumentNode, item);

                return document.DocumentNode.InnerHtml;
            }

         private HtmlNode ParseNode(HtmlDocument document, HtmlNode parentNode, ItemBase item)
        {
            var node = DefineNode(document, item);

            parentNode.ChildNodes.Add(node);

            if (item.Children.Count == 0)
                return node;

            foreach (var child in item.Children)
                ParseNode(document, node, child);

            return node;
        }

在这种情况下,在准备好的文档中,我在尝试访问 document.DocumentNode.InnerHtml 时得到了 Null 引用。但是 InnerText 反映的是实际文本,一切都好吗?

万一我document.LoadHtml("")同一个html,document.DocumentNode.InnerHtml无异常返回真实的html?

html:

<p>dsgwegsdrgsrdeg</p>
<p>&nbsp;</p>
<p>just <strong>typihere</strong></p>
<p>&nbsp;</p>
<ol>
   <li>some list</li>
   <li>another list</li>
</ol>
<p>j</p>

【问题讨论】:

    标签: c# html html-agility-pack nullreferenceexception


    【解决方案1】:

    问题出在这一行:

    parentNode.ChildNodes.Add(node);
    

    我们需要用

    替换它
    parentNode.AppendChild(node);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      相关资源
      最近更新 更多