WebSerives System.Xml.Serialization命名空间_空间

2020-02-27 其他范文 下载本文

WebSerives System.Xml.Serialization命名空间由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“空间”。

要使用.NET进行对象的序列化,必须在解决方案中添加System.Xml的引用,并且在类文件中引入System.Xml.Serialization命名空间。这样就可以在文件中使用序列化所需要的各种特性了。

Imports System.Xml.Serialization

如果对XML Serialization缺少了解,请首先参考拙文:在.NET中实现对象序列化

2005-04-05

对象序列化

上面的例子包含了典型的XML中常见的各种元素:XML声明、XML根节点、XML节点、XML属性、XML集合。除XML声明外,在.NET中都有对应的特性用于定义这些元素。这些特性包括:XmlRootAttribute、XmlTypeAttribute、XmlElementAttribute、XmlAttributeAttribute、XmlArrayAttribute和XmlArrayItemAttribute。另外,还有两个常用的特性,XmlIgnoreAttribute用于标记在对象序列化时需要被忽略的部分,XmlIncludeAttribute用于标记在生成XML Schema时需要包括的类型。

如果没有显式地标记任何特性,那么默认类的特性为XmlTypeAttribute、类成员的特性为XmlElementAttribute,且名称为类或类成员的名称。例如:

Public Cla Order

Public ID As String

Public OrderDate As String

End Cla

如果不做任何特性标记,使用下面的代码序列化时: Dim o As New Order

With o

.ID = 123456

.OrderDate = Date.Now.ToShortDateString

End With

Dim writer As New XmlTextWriter(“abc.xml”, Encoding.UTF8)

Dim serializer As New XmlSerializer(GetType(Order))

writer.Formatting = Formatting.Indented serializer.Serialize(writer, o)

序列化后的XML为:

123456

2005-4-11

可以看到,对应Order类,而和分别对应Order类中的字段ID和OrderDate。另外,多了一个XML声明和两个XML命名空间。

XML声明是.NET自动添加的,但是encoding是在XmlTextWriter中指定的,如果不指定encoding,那么XML声明只有。我使用的是.NET 1.1,这个版本中只支持XML 1.0版本。另外,如果不指定encoding,那么默认的编码可能也是UTF8(没找到相关的资料)。

.NET默认为Order类添加了XMLSchema和XMLSchema-instance两个W3C的命名空间。该命名空间也可以自己指定,方法是使用XmlSerializer的另一个Serialize方法。

Dim ns As New XmlSerializerNamespaces ns.Add(“”, “”)writer.Formatting = Formatting.Indented serializer.Serialize(writer, o, ns)

要将类序列化为XML节点:

_

Public Cla Order

‘ any code here.End Cla

要将类序列化为XML根节点:

_

Public Cla Order

‘ any code here.End Cla

当在类中同时使用XmlRootAttribute、XmlTypeAttribute时,序列化文档中的类型以XmlRootAttribute为准:

_

Public Cla Order

‘ any code here.End Cla

要将类成员序列化为XML节点:

_

Public ID As String

要将类成员序列化为XML属性:

_

Public ID As String

要将类成员序列化为XML集合:

_

Public Cla Order

_

Public ID As String

Public orderDate As String

_

Public Items As New ArrayList

End Cla

_

Public Cla OrderItem

Public Name As String

End Cla

使用特性的一个好处是:可以在代码和序列化的文档中使用不同的编码规范。

《WebSerives System.Xml.Serialization命名空间.docx》
将本文的Word文档下载,方便收藏和打印
推荐度:
WebSerives System.Xml.Serialization命名空间
点击下载文档
相关专题 空间 System WebSerives 空间 System WebSerives
[其他范文]相关推荐
    [其他范文]热门文章
      下载全文