【vb.net】System.Xml序列化与反序列
利用System.Xml.Serialization进行序列化与反序列化操作
System.Xml.Serialization能够很方便地将XML文件转换为对象,或者将对象转换为XML文件。
假设:我们有下列这样的一段XML
...
1.根据XML的结构创建对象
Public Class XmlDocPublic Property Node1 As S1Public Property Node2 As S2
End ClassPublic Class S1Public Property A1 As StringPublic Property A2 As StringPublic Property A3 As String
End ClassPublic Class S2Public Property B1 As DoublePublic Property B2 As IntegerPublic Property olist As List(Of O)
End ClassPublic Class OPublic Property C1 As StringPublic Property C2 As String
End Class
2.添加标记
注:当节点名称与变量名称相同时,可以省略(xxxName="xx")
Public Class XmlDocPublic Property Node1 As S1Public Property Node2 As S2
End ClassPublic Class S1Public Property A1 As StringPublic Property A2 As StringPublic Property A3 As String
End ClassPublic Class S2Public Property B1 As DoublePublic Property B2 As IntegerPublic Property olist As List(Of O)
End ClassPublic Class OPublic Property C1 As StringPublic Property C2 As String
End Class
3.读取XML文件并返回XmlDoc对象。
我们先封装一个静态函数
Public Shared Function Load(ByVal filePath As String, ByVal objectType As Type) As ObjectTryUsing reader As System.IO.StreamReader = New System.IO.StreamReader(filePath)Dim xs As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(objectType)Dim ret As Object = xs.Deserialize(reader)Return retEnd UsingCatch ex As ExceptionReturn NothingEnd Try
End Function
调用Load函数将读取XML文件并返回XmlDoc对象
Dim doc As XmlDoc
Dim path As String = "test.xml"
doc = CType(Load(path, GetType(XmlDoc)), XmlDoc)
4.将XmlDoc对象保存为XML文件
Public Shared Function Save(ByVal filePath As String, ByVal XMLObject As Object) As BooleanTryDim ser As XmlSerializer = New XmlSerializer(XMLObject.[GetType]())Dim writer As TextWriter = New StreamWriter(filePath)Dim ns As XmlSerializerNamespaces = New XmlSerializerNamespaces()ns.Add("", "")ser.Serialize(writer, XMLObject, ns)writer.Close()Return TrueCatch ex As ExceptionReturn FalseEnd Try
End Function
调用Save函数,将XmlDoc保存为Xml
Dim doc As XmlDoc = New XmlDoc()
Dim path As String = "test.xml"
Save(path, doc)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
