我怀疑这是可能的,但我很好奇。是否可以通过使用元素的标记名来填充属性值来反序列化xml?例如,给定xml:
<Test>
<List>
<Jake Type="Dog" />
<Mittens Type="Cat" />
</List>
</Test>
可能会产生如下列表:
Class Animal
Property Name As String
Property Type As String
End Class
Name Type
------- -------
Jake Dog
Mittens Cat
答案 0 :(得分:1)
因此,不是使用Xml Serializer,您可以通过以下方式使用XmlReader(XmlTextReader)解决它:
Class Animal
Public Property Name As String
Public Property Type As String
End Class
Function ReadDocument(filename As String) As List(Of Animal)
Dim lst As New List(Of Animal)
Dim doc As XmlReader
Using fs As FileStream = New FileStream(filename, FileMode.Open, FileAccess.Read)
doc = New Xml.XmlTextReader(fs)
While doc.Read()
If doc.NodeType <> XmlNodeType.Element Then
Continue While
End If
If Not String.Equals(doc.Name, "List") Then
Continue While
End If
While doc.Read()
If doc.NodeType = XmlNodeType.EndElement And String.Equals(doc.Name, "List") Then
Exit While
End If
If doc.NodeType <> XmlNodeType.Element Then
Continue While
End If
Dim ani As New Animal
ani.Name = doc.Name
If doc.MoveToAttribute("Type") Then
ani.Type = doc.Value
lst.Add(ani)
End If
End While
End While
End Using
Return lst
End Function
Sub Main()
Dim animals As List(Of Animal) = ReadDocument("./Animals.xml")
Console.WriteLine("{0}{1}{2}", "Name", vbTab, "Type")
For Each ani As Animal In animals
Console.WriteLine("{0}{1}{2}", ani.Name, vbTab, ani.Type)
Next
Console.ReadLine()
End Sub