如何在没有 WebBrowser 控件的情况下解析 VB.net 中的 XML 文档? [英] How to parse an XML document in VB.net without a WebBrowser control?

查看:28
本文介绍了如何在没有 WebBrowser 控件的情况下解析 VB.net 中的 XML 文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如何从按钮的单击事件打开 URL(即 XML 页面)并读取 XML 文档的内容,而不使用 WebBrowser 控件对其进行解析?

How can I open a URL (which is an XML page) from a button's click event, for instance, and read the contents of the XML document, without using a WebBrowser control to parse it?

推荐答案

除了像其他人建议的那样使用 XDocument 和 LINQ 之外,还有另外两种常见的解决方案.一种是使用XmlDocument和XPath,另一种是使用XML序列化.例如,如果您有以下 XML 文档:

In addition to using XDocument, and LINQ, as others have suggested, there are also two other common solutions. One is to use XmlDocument and XPath, and the other is to use XML serialization. For instance, if you had the following XML document:

<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book Title="Book 1">
    <Author>Author 1</Author>
    <Chapter>Chapter 1</Chapter>
    <Chapter>Chapter 2</Chapter>
  </Book>
  <Book Title="Book 2">
    <Author>Author 1</Author>
    <Chapter>Chapter 1</Chapter>
    <Chapter>Chapter 2</Chapter>
  </Book>
</Books>

然后你可以用 XmlDocument 解析它并像这样用 XPath 搜索它(其中 xml 是一个包含上述 XML 的字符串):

Then you could parse it with XmlDocument and search through it with XPath like this (where xml is a string containing the above XML):

Dim doc As New XmlDocument()
doc.LoadXml(xml)
Dim authorOfBook1 As String = doc.SelectSingleNode("/Books/Book[@Title = 'Book 1']/Author").InnerText
Dim booksByAuthor1 As XmlNodeList = doc.SelectNodes("/Books/Book[Author = 'Author 1']")
'etc.

或者,您可以使用序列化来加载 XML 文档,方法是首先在某些类中定义文档结构:

Or, you could use serialization to load the XML document by, first, defining the document structure in some classes:

Public Class Books
    <XmlElement("Book")> _
    Public Items As List(Of Book)
End Class

Public Class Book
    <XmlAttribute()> _
    Public Title As String

    <XmlElement("Author")> _
    Public Authors As List(Of String)

    <XmlElement("Chapter")> _
    Public Chapters As List(Of String)
End Class

然后将 XML 反序列化为该类型的对象:

And then deserialize the XML into an object of that type:

Dim serializer As XmlSerializer = New XmlSerializer(GetType(Books))
Using reader As StringReader = New StringReader(xml)
    Dim books As Books = CType(serializer.Deserialize(reader), Books)
    'Analyze contents in books object
End Using

这篇关于如何在没有 WebBrowser 控件的情况下解析 VB.net 中的 XML 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆