首页 > 解决方案 > 从 webbrowser 组件中读取 XML

问题描述

我有一个应用程序,它在 NavUserPassword 身份验证后为个人提供 webbrowser 组件中 XML 页面的预览,然后显示一个侧面板,将其解析为有意义的数据。但是,我似乎找不到通过字符串将所有 XML 从 webbrowser 组件中导出的有效方法。

没有身份验证的网页示例是https://services.odata.org/Northwind/Northwind.svc/

我在下面有这段代码,尽管它会抛出一个 MssingMemberExeption “未找到类型‘HTMLDocumentClass’的公共成员‘XMLDocument’。”

Private Sub WebBrowserAuthEx1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowserAuthExt1.DocumentCompleted
    Dim doc As XmlDocument = New XmlDocument()
    doc.LoadXml(WebBrowserAuthExt1.Document.DomDocument.XMLDocument) ' I throw MssingMemberExeption
    MessageBox.Show(doc.Value.ToString)
End Sub

如何在 webbrowser 中获取此 XML DOM 以提供所有 XML?

它与普通的网络浏览器相同,但 XML 必须在经过身份验证时从中出来,并且我不想对另一个流进行身份验证。

标签: xmlvb.netwebbrowser-controlmicrosoft-dynamics

解决方案


对于您提供的示例 URL,您可以使用类似于以下代码的内容获取 xml:

Dim xmlText As String = WebBrowser1.Document.All.Item(0).InnerText

编辑: OP 指出(在被拒绝的编辑中)上面返回的文本在某些行上返回“-”。这是源被格式化为树结构而不是XML 的结果。他们的解决方案如下:

' It also includes the code folding dashes, use the below to sanitize the data.
If xmlText <> Nothing Then
    xmlText = xmlText.Replace("- ", "")
End If

这种使用Replace可能会导致意外修改数据,我只是想提出以下替代方案,将潜在的更改限制在行的开头。

Dim sb As New System.Text.StringBuilder(xmlText.Length)
Using sr As New System.IO.StringReader(xmlText)
    Do While sr.Peek <> -1
        Dim line As String = sr.ReadLine()
        Dim startOfLineIndex As Int32 = sb.Length
        sb.AppendLine(line)
        If sb.Chars(startOfLineIndex) = "-"c Then sb.Chars(startOfLineIndex) = " "c
    Loop
End Using
xmlText = sb.ToString()

推荐阅读