HTMLAgilityPack don't preserves original empty tags

怎甘沉沦 提交于 2019-11-28 06:11:27

问题


If i have some empty tags like this

<td  width="15px"/>

Agility pack fixes them to be like

<td  width="15px"></td>

Is anything possible to do to override this behavior ?


回答1:


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.




回答2:


Set the OptionWriteEmptyNodes property to true on your HtmlDocument.




回答3:


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">


来源:https://stackoverflow.com/questions/4389638/htmlagilitypack-dont-preserves-original-empty-tags

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