簡體   English   中英

從xml字符串中排除特定標簽的功能

[英]Function to exclude specific tags from xml string

我給了一個帶有html標簽列表的XML字符串,例如“ <p>, <a>, <img>, <link> ”等。

現在,我想做一個泛型函數,在該函數中我將傳遞html標簽列表,或者也可以是一個我想從傳遞的XML字符串中排除的標簽。 函數將返回整個字符串,沒有排除的標記。

  public const String[] htmlTags = new String[] { "<p>", "a", "img" };
  string result = strString.ExcludeHTMLTags(htmlTags); //I will write the String extension not an issue, please suggest how to exclude tags from exisiting string.

編輯:

我正在嘗試下面的代碼:

/// <summary>
/// Remove HTML tags from string using char array.
/// </summary>
public static string StripTagsCharArray(string source, String[] htmlTags)
{
    char[] array = new char[source.Length];
    int arrayIndex = 0;
    bool inside = false;

    for (int i = 0; i < source.Length; i++)
    {
        foreach (String htmlTag in htmlTags)
        {
            char let = source[i];
            String tag = "<" + "htmlTag"; //How to handle this as this is character
            if (let == tag)
            {
                inside = true;
                continue;
            }
            if (let == '>')
            {
                inside = false;
                continue;
            }
            if (!inside)
            {
                array[arrayIndex] = let;
                arrayIndex++;
            }
        }
    }
    return new string(array, 0, arrayIndex);
}

編輯2:使用正則表達式

String[] htmlTags = new String[] { "a", "img", "p" };
private const string STR_RemoveHtmlTagRegex = "</?{0}[^<]*?>";
public static string RemoveHtmlTag(String input, String[] htmlTags)
{
    String strResult = String.Empty;
    foreach (String htmlTag in htmlTags)
    {
        Regex reg = new Regex(String.Format(STR_RemoveHtmlTagRegex, htmlTag.Trim()), RegexOptions.IgnoreCase);
        strResult = reg.Replace(input, String.Empty);
        input = strResult;
    }
    return strResult;
}

現在的問題是,它並沒有刪除標記的值,因此如果存在“正在測試

然后返回“測試”,我也想刪除帶有值的整個標簽。

將html轉換為DOM-tree並刪除名稱包含在給定排除標簽列表中的元素節點

您是否嘗試過HTML Agility Pack 它是一個敏捷的HTML解析器,可構建讀/寫DOM並支持純XPATH或XSLT(作為.NET代碼庫構建),該庫使您可以解析“網絡外” HTML文件,並且可以使用以下方式修復字符串:想要,修改DOM,添加節點,復制節點。

暫無
暫無

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

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