由 串行化XML(一) 可以知道XML的序列化(Serialization)。它是这样一个过程:得到一个对象,把对象转换为一个XML文档,并且保存它以供使用,或者把它传到网络上其他地方以供使用。在.NET中,XML serialization通过检查类的属性是否被标志为read/write来工作。只要有其中一个属性,该类的值就会被取出并插入到一个XML文档里去。反序列化(De-serialization)则是一个相反的过程。
将一个对象串行化为xml后,再并行化,使其还原为原来的对象有时,在并行的xml当中可能存在意外的xml节点。
如果不处理这些意外的xml 的节点,XmlSerializer将忽略这些意外的节点,如果要处理这些意外节点,可以使用XmlSerializer的一下事件进行处理:
¨ UnknownNode
¨ UnknownElement
¨ UnknownAttribute
¨ UnreferencedObject
现在将book.xml的格式更改为:
<?xml version="1.0" encoding="utf-8"?>
<Book id="001" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<BookID>1</BookID>
<BookName>数学</BookName>
<Exception>Some Text</Exception>
</Book>
我们增加了一些意外的节点、属性,然后执行并行化过程:
Dim serializer As New Xml.Serialization.XmlSerializer(GetType(bookShop))
AddHandler serializer.UnknownAttribute, AddressOf myUnknownAttribute
AddHandler serializer.UnknownElement, AddressOf myUnknownElement
AddHandler serializer.UnknownNode, AddressOf myUnknownNode
Dim reader As System.IO.StreamReader = New System.IO.StreamReader("E:\serializer\book.xml")
Dim a As bookShop = CType(serializer.Deserialize(reader), bookShop)
reader.Close()
Console.WriteLine("BookShop Name:" & a.BookName)
Console.WriteLine("BookShop ID:" & a.BookID)
Console.WriteLine("Print Enter to Exit.............")
Console.ReadLine()
我们同样增加了意外节点、属性的处理代码,执行结果为:
这样我们就可以查看那些意外的节点、属性的信息了。
另外,我们还可以灵活的控制串行化xml 的格式,这样可以很方便的与外部应用程序进行交换对象。我们可以在类中加入.NET Framework属性来控制串行化xml 的格式。
Imports System.Xml
Imports System.Xml.Serialization
<XmlRoot(elementname:="Root_Book", namespace:="URI:MylocalURI")> _
Public Class Book
<XmlElement(elementname:="Book_ID", namespace:="URI:MylocalURI")> Public BookID As Integer
<XmlAttributeAttribute(AttributeName:="Name")> _
Public BookName As String
<XmlText()> _
Public test_Text As String
<XmlIgnore()> _
Public IgnoreText As String
‘IgnoreText 将不被串行化
End Class
Module Serialization
<STAThread()> _
Public Sub main()
Dim book As New book
book.BookID = 1
book.BookName = "数学"
book.test_Text = "Some Text"
book.IgnoreText = "IgnoreText"
Dim serializer As New Xml.Serialization.XmlSerializer(GetType(book))
Dim writer As System.IO.StreamWriter = New System.IO.StreamWriter("E:\serializer\book.xml")
serializer.Serialize(writer, book)
writer.Close()
End Sub
End Module
则生成的XML格式为:
<?xml version="1.0" encoding="utf-8"?>
<Root_Book xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="数学" xmlns="URI:MylocalURI">
<Book_ID>1</Book_ID>
Some Text
</Root_Book>