刪除Html標籤,同時保留內部文本和
標籤

c# html-agility-pack html-parsing

我正在嘗試從HTML內容中刪除span,font,b,s,strike(和其他內部元素)標記,同時在其中保留text和<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>

熱門答案

對於這種HTML操作,有一個很棒的庫叫做HTML Agility Pack

這是一個類似的問題,它將指向正確的方向: Html Agility Pack - 刪除元素,但不是innerHtml



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因