.NET框架提供了System.Xml.Serialization.XmlSerializer类型,为将对象序列化为XML或将XML序列化为对象提供了很大支持
先定义一个InspectionType类
<Xml.Serialization.XmlRoot("TownInspectionType")> _ 'TownInspectionType是root 节点,也可以是 xml 某个节点。
Public Class InspectionType
Public FirstName As String
Public LastName As String
End Class
要解析的xml 例子
<?xml version="1.0"?>
<TownInspectionType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FirstName>John</FirstName>
<LastName>Evans</LastName>
</TownInspectionType>
OR
<TownInspectionType>
<FirstName>John</FirstName>
<LastName>Evans</LastName>
</TownInspectionType>
下面是定义好的泛型,其中xml 是需要反序列化的节点,T是Model的类型,例子中是TownInspectionType,它包括了两个字段。
Public Class DeSerializer(Of T)
Public Function DeserializeXML(ByVal xml As String) As T
Dim ser As New XmlSerializer(GetType(T))
Using ms As New MemoryStream(Encoding.Default.GetBytes(xml))
Using r As New StreamReader(ms)
Dim obj As T = DirectCast(ser.Deserialize(r), T)
Return obj
End Using
End Using
End Function
End Class
下面是调用:
Dim serializer = New DeSerializer(Of InspectionType)
Dim TownInspectionTypeModel As InspectionType= serializer.DeserializeXML(townInspectionTypesChildNode.InterXml)
这里只是给出了 反序列化单一的Model 如果xml 是:
<TownInspectionTypes>
<TownInspectionType>
<FirstName>John</FirstName>
<LastName>Evans</LastName>
</TownInspectionType>
<TownInspectionType>
<FirstName>lili</FirstName>
<LastName>denvy</LastName>
</TownInspectionType>
</TownInspectionTypes>
能否把TownInspectionType 转化成一个List(of TownInspectionType)形式呢? 欢迎抛砖!