2012-05-17 57 views
1

我想編碼一個vb.net函數從標籤中提取特定的文本內容;我寫了這個功能如何從.NET中的標籤中提取文本內容?

Public Function GetTagContent(ByRef instance_handler As String, ByRef start_tag As String, ByRef end_tag As String) As String 
    Dim s As String = "" 
    Dim content() As String = instance_handler.Split(start_tag) 
    If content.Count > 1 Then 
     Dim parts() As String = content(1).Split(end_tag) 
     If parts.Count > 0 Then 
      s = parts(0) 
     End If 
    End If 
    Return s 
End Function 

但它不工作,例如用下面的調試代碼

Dim testString As String = "<body>my example <div style=""margin-top:20px""> text to extract </div> <br /> another line.</body>" 

    txtOutput.Text = testString.GetTagContent("<div style=""margin-top:20px"">", "</div>") 

我只得到「身體>我的榜樣」的字符串,而不是「文字提取」

任何人都可以幫助我嗎? TNX提前


我寫了一個新的常規和下面的代碼工作不過,我想知道是否存在性能更好的代碼:

Dim s As New StringBuilder() 
    Dim i As Integer = instance_handler.IndexOf(start_tag, 0) 
    If i < 0 Then 
     Return "" 
    Else 
     i = i + start_tag.Length 
    End If 
    Dim j As Integer = instance_handler.IndexOf(end_tag, i) 
    If j < 0 Then 
     s.Append(instance_handler.Substring(i)) 
    Else 
     s.Append(instance_handler.Substring(i, j - i)) 
    End If 
    Return s.ToString 
+0

我寫了一個新的常規和下面的代碼工作不過,我想知道是否存在性能更好的代碼: 昏暗譯文]新的StringBuilder() 暗淡我作爲整數= instance_handler.IndexOf(START_TAG,0) 如果I <0然後 返回 「」 否則 I = I + start_tag.Length 結束如果 昏暗J所示整數= instance_handler.IndexOf(END_TAG,ⅰ) 在j <0,則 s.Append(instance_handler.Substring( i)) Else s.Append(instance_handler.Substring(i,j-i)) End If 返回s.ToString – Max

回答

2

XPath是完成這一任務的一種方式。我相信別人會建議LINQ。下面是使用XPath的例子:

Dim testString As String = "<body>my example <div style=""margin-top:20px""> text to extract </div> <br /> another line.</body>" 
Dim doc As XmlDocument = New XmlDocument() 
doc.LoadXml(testString) 
MessageBox.Show(doc.SelectSingleNode("/body/div").InnerText) 

顯然,更復雜的文檔可能需要比單純"/body/div"更復雜的XPath,但它仍然是相當簡單的。

如果您需要獲取與路徑匹配的多個元素的列表,可以使用doc.SelectNodes

相關問題