我需要将文件反序列化为vb.net对象。
<ANIMALS>
<ANIMAL NO = "1">Dog</ANIMAL>
<ANIMAL NO = "2">Cat</ANIMAL>
<ANIMAL NO = "3">Cow</ANIMAL>
<ANIMAL NO = "4">Fish</ANIMAL>
</ANIMALS>
我有一个名为clsANIMALS的类,其中一个属性返回动物列表:
<Serializable()> _
<System.Xml.Serialization.XmlRoot("ANIMALS")> _
Public Class clsANIMALS
<System.Xml.Serialization.XmlElement("ANIMAL")> _
Public Property lstAnimal() As List(Of clsAnimal)
和一个名为clsANIMAL的子类,它具有属性的属性&#34; NO&#34;:
<Serializable()> _
<System.Xml.Serialization.XmlRoot("ANIMAL")> _
Public Class clsANIMAL
<System.Xml.Serialization.XmlAttribute("NO")> _
Public Property iNoAnimal() As Integer
有人可以告诉我如何对Dog,Cat等文本进行反序列化吗?
答案 0 :(得分:3)
您可以使用XmlTextAttribute获取值:
<Serializable()> _
<System.Xml.Serialization.XmlRoot("ANIMAL")> _
Public Class clsANIMAL
<System.Xml.Serialization.XmlAttribute("NO")> _
Public Property iNoAnimal() As Integer
<System.Xml.Serialization.XmlText()> _
Public Property strName As String
End Class
然后,您可以反序列化XML文件并使用strName
显示名称:
Dim stream = System.IO.File.OpenRead("Animals.xml")
Dim serializer = New System.Xml.Serialization.XmlSerializer(GetType([clsANIMALS]))
Dim animals As clsANIMALS = serializer.Deserialize(stream)
For Each animal In animals.lstAnimal
Console.WriteLine(animal.strName)
Next