【问题标题】:Get string inside html tag - VB.Net获取 html 标签内的字符串 - VB.Net
【发布时间】:2017-02-02 06:12:40
【问题描述】:

所以,我有这个 html 代码:

<div class="keyboard">
  <p>
    Hello world!
  </p>
</div>

我想得到文本“Hello world!”。我已尝试使用下面的正则表达式代码,但它不起作用。

Dim findtext2 As String = "(?<=<div class=""keyboard"">)(.*?)(?=</div>)"
Dim myregex2 As String = TextBox1.Text 'HTML code above
Dim doregex2 As MatchCollection = Regex.Matches(myregex2, findtext2)
Dim matches2 As String = ""
For Each match2 As Match In doregex2
    matches2 = matches2 + match2.ToString + Environment.NewLine
Next
MsgBox(matches2)

【问题讨论】:

  • 在我看来,您在第 2 行缺少结束引号。实际上不是 .NET 专家,所以我可能是错的:P
  • ' 字符用于 cmets,不需要结尾。
  • 嗯,这很令人困惑。在基本上所有其他语言中,它要么是语法错误,要么是字符串/字符文字。
  • 忽略那条评论,它是给人们阅读代码的,它也不影响它。
  • 用正则表达式提取 html 很麻烦,而且容易出错。也许试试the html agility pack。或者,如果它是 xhtml,则使用 xml api 之一

标签: html vb.net


【解决方案1】:

正如在 cmets 中提到的,不要使用正则表达式来解析 html 代码。
而是使用 LINQ to XML

Dim html As XElement =
    <html>
        <body>
            <div class = "keyboard">
                <p>Hello word!</p>
            </div>
        </body>
    </html>

Dim values As String = 
    html.Descendants("div").
         Where(Function(div) div.Attribute("class").Value.Equals("keyboard")).
         Select(Function(div) div.Element("p").Value)

For Each value As String in values
    Console.WriteLine(value);
End For

【讨论】:

  • 给出错误(在第一行):“String”类型的值无法转换为“System.Xml.Linq.XElement”
  • 你是否用引号包裹了 html 代码?如果是这样,请删除引号。 XML Literals Overview (Visual Basic)
  • 我已经把它放在了 TextBox 中并写了 Dim html As XElement = TextBox1.Text.
  • 然后使用Dim html As XElement = XElement.Parse(TextBox1.Text);
猜你喜欢
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 2012-11-07
  • 2010-10-24
  • 2011-08-21
  • 1970-01-01
相关资源
最近更新 更多