如何在没有WebBrowser控件的情况下解析VB.net中的XML文档?

时间:2012-08-10 17:58:16

标签: xml vb.net

如何从按钮的click事件中打开URL(这是一个XML页面),并读取XML文档的内容,而不使用WebBrowser控件来解析它?

3 个答案:

答案 0 :(得分:1)

要解析XML,您可以使用 LINQtoXML 库(.Net Framework 3.5以后)

例如,如果您有以下格式的XML,

<rss>
  <report name="rpt1">
    <title>AAA</title>
    <image>some1</image>   
  </report>
  <report name="rpt2">
    <title>BBB</title>
    <image>some3333</image>   
</rss>

此代码将对其进行解析并获取title&amp;每个url项目report

Dim path As String = "pathTosomexml.xml"
Dim elm As XElement = XElement.Load(path)
If elm IsNot Nothing Then

    For Each page As var In elm.Elements("report")
        Dim title = page.Element("title").Value
        Dim url = page.Element("image").Value

    Next
End If

答案 1 :(得分:1)

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

<?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的字符串):

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文档,首先,在某些类中定义文档结构:

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反序列化为该类型的对象:

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

答案 2 :(得分:0)

使用XDocument将其加载到XDocument.Load

这将为您解析文档,以便您可以使用LINQ to XML进行查询。