-- 作者:guoyan1981
-- 发布时间:4/5/2004 2:45:00 PM
-- 串行化xml(三)
由 串行化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>
|