在保留内部文本和标签的同时删除Html标签

时间:2012-11-16 22:12:56

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

我正在尝试从HTML内容中删除span,font,b,s,strike(和其他内部元素)标记,同时保留其中的文本和<br>标记。为此,我正在使用HTML敏捷包。我设法保留了文字,但<br>标签仍然存在问题。有什么想法吗?

以下是代码:

 private void removeTagsButPreserveText2(HtmlNode nodeToRemove)
    {
        var parent = nodeToRemove.ParentNode;
        var prev = nodeToRemove.PreviousSibling;

        if (prev != null)
        {
            var child = nodeToRemove.SelectNodes("./br");

            if (child == null)
            {
                parent.InsertAfter(documentToSearch.CreateTextNode(nodeToRemove.InnerText + " "), prev);

                nodeToRemove.Remove();
            }
            else
            {
                foreach (var item in child)
                {
                    var parent2 = item.PreviousSibling;

                    if (parent2 != null)
                    {
                        if (parent2.InnerText.HasDate())
                        {
                            var newNode = parent.InsertAfter(documentToSearch.CreateTextNode(parent2.InnerText), prev);
                            parent.InsertAfter(documentToSearch.CreateElement("br"), newNode);
                            nodeToRemove.Remove();
                        }
                    }
                }
            }
        }
    }

例如,输入将是:

<p><font face="Arial" size="2"><strike>
        <span style="font-weight: 400"><font color="#000000">Paper 
        Submission (Full 
        Paper) Before
        <span lang="en-us">September</span> 20, 201<span lang="en-us">2</span></font></span></strike><font color="#FF0000"><br>
        Notification of 
        Acceptance On <span lang="en-us">October 5</span>, 201<span lang="en-us">2</span><br>
        Authors' 
        Registration Before
        <span lang="en-us">October 20</span>, 201<span lang="en-us">2</span><br>
        ICNIT 2012 Conference 
        Dates November 
        17 - 18, 2012</font></font></p>

,输出应如下所示:

<p>Paper Submission (Full Paper) Before September 20, 2012<br>
        Notification of Acceptance On October 5, 2012<br>
        Authors' Registration Before October 20, 2012<br>
        ICNIT 2012 Conference 
        Dates November 
        17 - 18, 2012</p>

2 个答案:

答案 0 :(得分:0)

您是否尝试使用正则表达式?我的意思是,把所有内容都变成“<xxxx asdasd>”或类似内容并替换每个“”只维护<BR>

答案 1 :(得分:0)

对于这种HTML操作,有一个很棒的库叫HTML Agility Pack

这是一个类似的问题,它将指向正确的方向:Html Agility Pack - Remove element, but not innerHtml