【问题标题】:How to split ul list into List<string> with li using class or another attribute如何使用类或其他属性将 ul 列表拆分为带有 li 的 List<string>
【发布时间】:2019-02-01 20:22:22
【问题描述】:

我有一个 html ul 列表:

<ul>
<li class="ng-scope">Item 1</li>
<li class="ng-scope">Item 2</li>
<li class="ng-scope">Item 3</li>
</ul>

我想在 C# 中将其转换为 List&lt;string&gt;li 元素可以有一个属性,也可以没有。例如。可以是&lt;li class="ng-scope"&gt; 或只是&lt;li&gt;

我目前正在这样做:

            string patternUL = @"<(ul|ol)[\s]*[^\>]*>(<li[ a-z=""\\]*>.*?</li>)+?</\1>";
            string trg = Regex.Replace(source, patternUL, (param) =>
            {
                foreach (Capture c in param.Groups[2].Captures)
                {
                    output += $"{Regex.Replace(c.Value.Replace("&amp;", "&"), "<li>(.*?)</li>", "$1")}|";
                }
                //}
                return output;
            });

但我没有将列表拆分为字符串 List - 它与模式不匹配。 如果我通过 li 没有任何属性的 ul 列表,那么它可以正常工作。

【问题讨论】:

    标签: c# regex list html-lists


    【解决方案1】:

    不建议使用正则表达式解析html。而是使用像HTML agility pack 这样的框架。这样做你可以得到所有&lt;li&gt;&lt;/li&gt; 这样的列表:

    var html = @"
        <ul>
           <li class=""ng-scope"">Item 1</li>
           <li class=""ng-scope"">Item 2</li>
           <li class=""ng-scope"">Item 3</li>
        </ul>";
    
    var doc = new HtmlDocument();
    doc.LoadHtml(html);
    
    var list = new List<string>(doc.DocumentNode.SelectNodes("//li").Select(li => li.InnerText));
    

    【讨论】:

      【解决方案2】:

      我建议你使用 HtmlAgilityPack 来解析 html :

      HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
      doc.LoadHtml(File.ReadAllText("test.txt")); // here you can give a normal string
      foreach (var li in doc.DocumentNode.SelectNodes("//li")) // select li only
      {
          output += li.InnerText; // here do what you want to do
      }
      

      它捕获以下文本:

      Item1
      Item2
      Item3
      

      【讨论】:

        猜你喜欢
        • 2019-01-14
        • 2016-07-31
        • 2014-12-25
        • 2018-09-14
        • 2020-02-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-12
        • 2022-01-02
        相关资源
        最近更新 更多