使用XmlReader从VB.NET中的XML文件获取名称和值

时间:2018-06-28 00:29:41

标签: xml vb.net xmlreader

我正在使用以下XML文件和VB代码。我希望能够获得项目标签中的项目名称,以及标签之间的任何值。获取“名称”值可以很好地工作,但是我似乎无法弄清楚如何读取任何子项。我想用2列数据填充ListView或可能的DataGrid:

RequestMessage1

XML文件:

Response1

此代码的奇怪之处在于“ IF”测试通过,这意味着xr.Name必须为“ project”。但是,我的日志测试行(xr.Name.ToString)显示.Name为“描述”。我不明白。

project   |  description
------------------------
file001   |  ABC Project
file002   |  DEF Project

2 个答案:

答案 0 :(得分:1)

我为您的XML编写了此代码,以获取文件名(项目/名称)和标题(说明)。我希望你能理解:)

Dim filename As String = ""
Dim title As String = ""
Dim XMLReader As XmlReader = XMLReader.Create(xmlfile)
With XMLReader
    'As long as the reader hasnt come to the end of the document, this loop is executed'
    Do While .Read
    If .IsStartElement() Then
        Select Case .Name
        Case "project"
            filename = .GetAttribute(0)
            Console.WriteLine(filename)
        Case "description"
            title = .ReadElementString
            Console.WriteLine(title)
            Console.WriteLine("Found: " & filename & " - " & title) 
            'you can place your "final" code here.'
            Exit Select
        Case Else
            .Read()
            'continue reading if nothing is special'
        End Select
    End If
    Loop
    .Close() 'close the reader. All done!'
End With

您可以在此处测试代码:https://dotnetfiddle.net/3CDd6Q

在您的原始代码中有一些错误,例如您使用xr.Name来获取描述标签的元素,但是使用.Name时,您只会得到<name>标签的名称。如果要获取.ReadElementString标签之间的元素,则需要使用<>element<>

答案 1 :(得分:1)

您可以让VS创建一个与XML文件相对应的类,然后可以使用该类来获取数据,有时非常简单。

我将DataGridView放在窗体上并使用了以下代码:

Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization

Public Class Form1

    Class Project
        Property Filename As String
        Property Description As String
    End Class

    Private Sub LoadData()
        Dim xmlFile = "C:\temp\projectlist.xml"
        Dim projectsData As Projects.menu

        Dim serializer = New XmlSerializer(GetType(Projects.menu))
        Using fs As New FileStream(xmlFile, FileMode.Open, FileAccess.Read, FileShare.Read)
            Using rdr = XmlReader.Create(fs)
                projectsData = DirectCast(serializer.Deserialize(rdr), Projects.menu)
            End Using
        End Using

        Dim projectsList = projectsData.project.Select(Function(p) New Project With {.Filename = p.name, .Description = p.description}).ToList()

        DataGridView1.DataSource = projectsList

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        LoadData()
        DataGridView1.AutoResizeColumn(0)
        DataGridView1.AutoResizeColumn(1)

    End Sub

End Class

要获取此信息:

enter image description here

请根据需要调整类和属性的名称。

当然,您需要该类与XML文件一起使用。为此,请复制XML数据,然后在Visual Studio中选择“编辑”->“选择性粘贴”->“将XML粘贴为类”。我选择将其粘贴到名为“ Projects”的类中,并得到以下信息:

Public Class Projects

    <System.SerializableAttribute(),
 System.ComponentModel.DesignerCategoryAttribute("code"),
 System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=True),
 System.Xml.Serialization.XmlRootAttribute([Namespace]:="", IsNullable:=False)>
    Partial Public Class menu

        Private headerField As menuHeader

        Private projectField() As menuProject

        '''<remarks/>
        Public Property header() As menuHeader
            Get
                Return Me.headerField
            End Get
            Set
                Me.headerField = Value
            End Set
        End Property

        '''<remarks/>
        <System.Xml.Serialization.XmlElementAttribute("project")>
        Public Property project() As menuProject()
            Get
                Return Me.projectField
            End Get
            Set
                Me.projectField = Value
            End Set
        End Property
    End Class

    '''<remarks/>
    <System.SerializableAttribute(),
System.ComponentModel.DesignerCategoryAttribute("code"),
System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=True)>
    Partial Public Class menuHeader

        Private listnameField As String

        Private lastlistupdateField As String

        '''<remarks/>
        Public Property listname() As String
            Get
                Return Me.listnameField
            End Get
            Set
                Me.listnameField = Value
            End Set
        End Property

        '''<remarks/>
        Public Property lastlistupdate() As String
            Get
                Return Me.lastlistupdateField
            End Get
            Set
                Me.lastlistupdateField = Value
            End Set
        End Property
    End Class

    '''<remarks/>
    <System.SerializableAttribute(),
System.ComponentModel.DesignerCategoryAttribute("code"),
System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=True)>
    Partial Public Class menuProject

        Private descriptionField As String

        Private monthField As String

        Private nameField As String

        Private indexField As Boolean

        Private imageField As String

        '''<remarks/>
        Public Property description() As String
            Get
                Return Me.descriptionField
            End Get
            Set
                Me.descriptionField = Value
            End Set
        End Property

        '''<remarks/>
        Public Property month() As String
            Get
                Return Me.monthField
            End Get
            Set
                Me.monthField = Value
            End Set
        End Property

        '''<remarks/>
        <System.Xml.Serialization.XmlAttributeAttribute()>
        Public Property name() As String
            Get
                Return Me.nameField
            End Get
            Set
                Me.nameField = Value
            End Set
        End Property

        '''<remarks/>
        <System.Xml.Serialization.XmlAttributeAttribute()>
        Public Property index() As Boolean
            Get
                Return Me.indexField
            End Get
            Set
                Me.indexField = Value
            End Set
        End Property

        '''<remarks/>
        <System.Xml.Serialization.XmlAttributeAttribute()>
        Public Property image() As String
            Get
                Return Me.imageField
            End Get
            Set
                Me.imageField = Value
            End Set
        End Property
    End Class


End Class

P.S。我将编码放入XML文件的声明中:<?xml version="1.0" encoding="utf-8" ?>