簡體   English   中英

HTML Strip功能

[英]HTML Strip Function

有一個很難破解的堅果。

我有一個HTML,需要刪除一些標簽,屬性和屬性

基本上,要考慮三種不同的方法:

  • 字符串操作:遍歷HTML字符串,並通過“手動”字符串操作剝離它
  • 正則表達式: 使用RegEx解析HTML是邪惡的。 剝離HTML也是邪惡的嗎?
  • 使用庫來剝離它(例如HTML Agility Pack)

我希望我有以下清單:

  • acceptedTags(例如SPAN,DIV,OL,LI)
  • acceptedAttributes(例如STYLE,SRC)
  • 接受的屬性(例如,文本對齊,字體重量,顏色,背景顏色)

我可以傳遞給剝離HTML的此函數。

輸入示例:

<BODY STYLE="font-family:Tahoma;font-size:11;"> <DIV STYLE="margin:0 0 0 0;text-align:Left;font-family:Tahoma;font-size:16;"> <SPAN STYLE="font-weight:bold;color:#000000;background-color:#FF0000;font-family:tahoma;font-size:11;">Hello</SPAN></BODY>

示例輸出(帶有上面的參數列表):

<DIV STYLE="text-align:Left;"> <SPAN STYLE="font-weight:bold;color:#000000;background-color:#FF0000;">Hello</SPAN>
  1. 整個標簽正文被剝離(不接受標簽)
  2. 屬性邊距,字體系列和字體大小已從DIV標簽中剝離
  3. 從SPAN-Tag中刪除了font-family和font-size屬性。

我嘗試了什么?

乍看之下,正則表達式似乎是最好的方法。 但是我無法使其正常運行。 我看過關於Stackoverflow的文章:

...還有很多。

我嘗試了以下正則表達式:

Dim AcceptableTags As String = "font|span|html|i|b|u|sup|sub|ol|ul|li|br|h2|h3|h4|h5|span|div|p|a|img|blockquote"
            Dim WhiteListPattern As String = "</?(?(?=" & AcceptableTags & _
                  ")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:([""']?).*?\1?)?)*\s*/?>"
Dim Html as String = Regex.Replace(b.HTML, WhiteListPattern, "", RegexOptions.Compiled)

但是,這僅刪除標簽,而沒有屬性或屬性!

我絕對不是在尋找可以完成整個工作的人。 而是為某人指出了我正確的方向。

我對C#或VB.NET的回答感到滿意。

絕對使用圖書館! (看這個

有了HTMLAgilityPack,您幾乎可以做任何您想做的事情:

  1. 刪除不需要的標簽:

     string[] allowedTags = {"SPAN", "DIV", "OL", "LI"}; foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//node()")) { if (!allowedTags.Contains(node.Name.ToUpper())) { HtmlNode parent = node.ParentNode; parent.RemoveChild(node,true); } } 
  2. 刪除不需要的屬性並刪除屬性

     string[] allowedAttributes = { "STYLE", "SRC" }; foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//node()")) { List<HtmlAttribute> attributesToRemove = new List<HtmlAttribute>(); foreach (HtmlAttribute att in node.Attributes) { if (!allowedAttributes.Contains(att.Name.ToUpper())) attributesToRemove.Add(att); else { string newAttrib = string.Empty; //do string manipulation based on your checking accepted properties //one way would be to split the attribute.Value by a semicolon and do a //String.Contains() on each one, not appending those that don't match. Maybe //use a StringBuilder instead too att.Value = newAttrib; } } foreach (HtmlAttribute attribute in attributesToRemove) { node.Attributes.Remove(attribute); } } 

我實際上可能只是將自己寫成一個多步驟過程:

1)排除所有從標記中刪除要刪除的標記的屬性的規則(標記將不會在那里!)

2)遍歷文檔,獲取文檔的副本(不含排除的標記)(即,在您的示例中,將所有內容復制到“ <div”,然后等待直到看到“>”,然后再繼續復制。如果我處於復制模式,並且看到“ ExcludedTag =“,然后停止復制,直到看到引號為止。

在運行此過程之前,您可能需要對html進行一些工作前驗證,並設置相同的格式等,以避免輸出損壞。

哦,分塊復制,即只保留復制索引直到到達復制結束,然后復制整個塊,而不是單個字符!

希望這可以作為起點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM