[英]How to split a string with between different delimiters in vb.net
我想在例如<product>
和</product>
之間拆分一個字符串。 字符串中可能有幾千種產品。
例子:
<Product xmlns="">
<Code>021-05402</Code>
</Product>
<Product xmlns="">
<Code>022-05402</Code>
</Product>
我嘗試了一個 xml 解析器,但是 xml 格式不正確並且出現了很多錯誤。
首先,我會找出為什么XML 格式不正確,因為這對解決您的問題大有幫助,然后您可以非常輕松地解析 XML 字符串。 正如評論中所建議的, HTML Agility Pack可能是一種前進的方式:
這是一個敏捷的 HTML 解析器,它構建了一個讀/寫 DOM 並支持普通的 XPATH 或 XSLT(你實際上不必了解 XPATH 或 XSLT 來使用它,別擔心......)。 它是一個 .NET 代碼庫,允許您解析“網絡之外”的 HTML 文件。 解析器對“現實世界”格式錯誤的 HTML 非常寬容。 對象模型與 System.Xml 建議的非常相似,但用於 HTML 文檔(或流)。
或者,我過去不得不求助於某些事情,您可以遍歷字符串並使用IndexOf和SubString檢索值:
Dim xml As String = "<Product xmlns=""> <Code>021-05402</Code> </Product> <Product xmlns=""> <Code>022-05402</Code> </Product>"
Dim startPos As Integer = 0
Dim endPos As Integer = 0
Dim codes As New List(Of String)
While True
startPos = xml.IndexOf("<Code>", endPos)
endPos = xml.IndexOf("</Code>", endPos) + 7 '7 is the length of </Code> and I want to include this
If startPos > 0 Then
Try
'would be worth implementing a check that the indexes aren't going to cause a problem
codes.Add(xml.Substring(startPos, endPos - startPos))
Catch ex As ArgumentOutOfRangeException
'Handle the exception
End Try
Else
Exit While
End If
End While
codes
將包含基於您的示例 XML 的兩個項目:
<Code>021-05402</Code>
<Code>022-05402</Code>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.