HTMLAgilityPack don't preserves original empty tags

早过忘川 提交于 2019-11-29 12:45:23

Try this before saving:

if (HtmlNode.ElementsFlags.ContainsKey("td"))
{
    HtmlNode.ElementsFlags["td"] = HtmlElementFlag.Empty | HtmlElementFlag.Closed;
}
else
{
    HtmlNode.ElementsFlags.Add("td", HtmlElementFlag.Empty | HtmlElementFlag.Closed);
}

This changes the behavior for all td elements which may not be what you want. I don't know of a way to accomplish this per-node.

Pittfall

Set the OptionWriteEmptyNodes property to true on your HtmlDocument.

While @Corbin March's answer doesn't work as desired, it's the only one I've found that comes close. The problem is that HAP still does some additional fixup that makes this a problem.

From the original code:

<td  width="15px"/>

By set the ElementFlags as above the closing element tag indeed is not created, however the original trailing "/" is removed. This could be a problem depending on your scenario, it was for me. The original fragment becomes:

<td  width="15px">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!