【问题标题】:Read XML from a webbrowser component从 webbrowser 组件中读取 XML
【发布时间】:2018-09-20 20:08:51
【问题描述】:

我有一个应用程序,它在 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必须在经过身份验证后从中出来,我不想对另一个流进行身份验证。

【问题讨论】:

    标签: xml vb.net webbrowser-control microsoft-dynamics


    【解决方案1】:

    对于您提供的示例 Url,您可以使用类似以下代码的方式获取 xml:

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

    编辑:OP 指出(在被拒绝的编辑中)上面返回的文本在某些行上返回“-”。这是源被格式化为树结构而不是 pure 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()
    

    【讨论】:

    • @DevSushi,您的编辑被拒绝,但我收到了消息。请查看修改后的答案,因为您的解决方案存在一些风险。
    【解决方案2】:

    如果这是内置的System.Windows.Forms.WebBrowser 控件,您可以使用DocumentText property 获取网站的HTML(基本上是XML)代码。

    doc.LoadXml(WebBrowserAuthExt1.DocumentText)
    

    【讨论】:

    • 我得到一个 XmlException 'Reference to undeclared entity 'nbsp'。行#,位置#。在这行代码中,XmlDocument 是否需要对 XML 进行清理?
    • @DevSushi :看起来是这样。 &amp;nbsp; 是 HTML 中的不间断空格。我不完全确定 Tn 的解决方案是如何工作的,但是在使用 InnerText 时,通常会为您转换此类实体,因此它可以解决该问题。
    猜你喜欢
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多