消除<>之间的所有内容标签

时间:2015-10-29 08:55:28

标签: vb.net

我有一组html格式的非常大的文本,我希望消除标记<><>之间的所有内容。在标签的外侧某处有一个名称,我希望得到,如<a><a><a>name<a/><a/><a/>。 我写了一个小程序,我插入了我的长文本,按下按钮,我得到文本,将开始子串到下一个>,然后是content.Length来自最后> 1}}直到下一个<大于1,然后我将其插入列表中。

基本上我想获取<>标签中没有的所有名称并将它们放在列表中。我的参赛者都参加了比赛。

事情是代码不能完全按照我的希望工作。它需要一个小小的调整,我有点困惑。

这是我的代码:

Private Sub btnPickWinner_Click(sender As Object, e As EventArgs) Handles btnPickWinner.Click
    Dim vContestant As String = ""
    Dim vAllText As String = tbxText.Text
    Dim vList As New List(Of String)
    Dim vLength As Integer
    Dim vStrToCountLength As String
    While vAllText.Length > 1
        vStrToCountLength = vAllText.Substring(0, vAllText.IndexOf(">"))
        vLength = vAllText.Length - vStrToCountLength.Length
        vAllText = vAllText.Substring(vAllText.IndexOf(">"), vLength)
        vContestant = vAllText.Substring(0, vAllText.IndexOf("<"))
        If (vContestant.Length > 1) Then
            vList.Add(vContestant)
        End If
    End While
End Sub

以下是我的文字的一小部分示例:

<div class="_6a"><div class="_6a _6b" style="height:50px"></div><div class="_6a _6b"><div class="fsl fwb fcb"><a href="abcde.com/?fref=pb&amp;hc_location=profile_browser"; data-gt="{&quot;engagement&quot;:{&quot;eng_type&quot;:&quot;1&quot;,&quot;eng_s‌​rc&quot;:&quot;2&quot;,&quot;eng_tid&quot;:&quot;673597072&quot;,&quot;eng_data&q‌​uot;:[]}}" data-hovercard="/ajax/hovercard/user.php?id=673597072&amp;extragetparams=%7B%22h‌​c_location%22%3A%22profile_browser%22%7D">Antonis Lambr</a></div></div></div></div></div></div></li> 

所以我只想得到“Antonis Lambr”这个名字。 我的文字超过一百万字,所以我只是在这里粘贴了一个非常小的样本......

1 个答案:

答案 0 :(得分:2)

你应该not use string methods or regex to parse HTML。而是使用像HtmlAgilityPack这样的库:

Dim html = "<div class=""_6a""><div class=""_6a _6b"" style=""height:50px""></div><div class=""_6a _6b""><div class=""fsl fwb fcb""><a href=""abcde.com/?fref=pb&amp;hc_location=profile_browser""; data-gt=""{&quot;engagement&quot;:{&quot;eng_type&quot;:&quot;1&quot;,&quot;eng_s‌​rc&quot;:&quot;2&quot;,&quot;eng_tid&quot;:&quot;673597072&quot;,&quot;eng_data&q‌​uot;:[]}}"" data-hovercard=""/ajax/hovercard/user.php?id=673597072&amp;extragetparams=%7B%22h‌​c_location%22%3A%22profile_browser%22%7D"">Antonis Lambr</a></div></div></div></div></div></div></li>"
Dim doc = New HtmlAgilityPack.HtmlDocument()
doc.LoadHtml(html)

Dim anchorsTexts = From a In doc.DocumentNode.SelectNodes("//a[@href]")
                   Select a.InnerText
Dim anchorTextList = anchorsTexts.ToList()

或使用以下语法:

Dim anchorsTexts = From a In doc.DocumentNode.Descendants("a")
                   Where Not String.IsNullOrEmpty(a.GetAttributeValue("href", ""))
                   Select a.InnerText
Dim anchorTextList = anchorsTexts.ToList()

该列表包含一个字符串Antonis Lambr,它是锚文本。

相关问题