这是我的XML文件:
<?xml version="1.0" encoding="utf-8"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>test</name>
<one>1</one>
<two>2</two>
</test>
这是我的代码:
Imports System.Xml.Serialization
Imports System.IO
Class main
Sub Main()
Dim p As New test()
Dim x As New XmlSerializer(p.GetType)
Dim objStreamReader As New StreamReader("XML.xml")
Dim p2 As New class1()
p2 = x.Deserialize(objStreamReader)
objStreamReader.Close()
MsgBox(p2.name)
MsgBox(p2.one)
MsgBox(p2.two)
End Sub
End Class
我的班级:
Imports System.Xml.Serialization
Public Class test
Private newname As String
Private newone As Integer
Private newtwo As Integer
Public Property name() As String
Get
name = newname
End Get
Set(ByVal value As String)
newname= value
End Set
End Property
Public Property one() As Integer
Get
one = newone
End Get
Set(ByVal value As Integer)
newone = value
End Set
End Property
Public Property two() As Integer
Get
two = newtwo
End Get
Set(ByVal value As Integer)
newtwo = value
End Set
End Property
End Class
它有效,它给我带有XML文件中数据的消息框,但是我遇到了麻烦,如果我将内部节点添加到XML文件中:
<?xml version="1.0" encoding="utf-8"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>test</name>
<numbers>
<one>1</one>
<two>2</two>
</numbers>
</test>
我该如何处理数字?我知道它是测试的属性,但它也是一个类,因为它有一个和两个作为属性,那么正确的方法是什么?
更新
<?xml version="1.0" encoding="utf-8"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>test</name>
<numbers>
<one>1</one>
<two>2</two>
</numbers>
<numbers>
<one>3</one>
<two>4</two>
</numbers>
</test>
答案 0 :(得分:1)
要反序列化该示例XML,您希望您的数据类看起来像这样:
Public Class test
Private newname As String
Private newnumbers As List(Of Numbers)
Public Property name() As String
Get
Return newname
End Get
Set(ByVal value As String)
newname = value
End Set
End Property
<XmlElement()> _
Public Property numbers() As List(Of Numbers)
Get
Return newnumbers
End Get
Set(ByVal value As List(Of Numbers))
newnumbers = value
End Set
End Property
End Class
Public Class Numbers
Private newone As Integer
Private newtwo As Integer
Public Property one() As Integer
Get
Return newone
End Get
Set(ByVal value As Integer)
newone = value
End Set
End Property
Public Property two() As Integer
Get
Return newtwo
End Get
Set(ByVal value As Integer)
newtwo = value
End Set
End Property
End Class
然后你可以像这样反序列化它:
Sub Main()
Dim p As New test()
Dim x As New XmlSerializer(p.GetType)
Dim objStreamReader As New StreamReader("XML.xml")
Dim p2 As New test()
p2 = x.Deserialize(objStreamReader)
objStreamReader.Close()
MsgBox(p2.name)
For Each i As Numbers In p2.numbers
MsgBox(i.one)
MsgBox(i.two)
Next
End Sub