如何在 VB.NET 中编写易于 XML 序列化的对象? [英] How do I write objects for easy XML Serialization in VB.NET?

查看:26
本文介绍了如何在 VB.NET 中编写易于 XML 序列化的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 VB.NET 编写一个小应用程序,我希望其中的一些类能够将自己写出到 XML 中以用作保存"功能.我见过 XSD 文件用于生成 VB 类,这些类可以很容易地将自己序列化为 XML 和从 XML 序列化.如果我确实有任何需要符合的预先存在的 XML 格式,我将如何执行此操作,因为我只是自己创建类?

I'm writing a small application in VB.NET and I would like some of the classes to be able to write themselves out to XML to serve as a "save" feature. I have seen XSD files used to generate VB classes that can serialize themselves into and out of XML very easily. How would I do this if I do have any pre-existing XML format that I need to conform to as I'm just creating the classes myself?

推荐答案

使用 System.Xml 和 System.Xml.Serialization 命名空间.它们描述了类,您可以使用这些类为类的成员添加相应的标签.

Use the System.Xml and System.Xml.Serialization namespaces. They describe classes that you can use to annotate your classes' members with the corresponding tag.

例如(在 C# 中):

For example (in C#):

[XmlRoot("foo")]
public class Foo
{
     [XmlAttribute("bar")] 
     public string bar;
     [XmlAttribute("baz")] 
     public double baz;
}

或在 VB.NET 中(可能在语法上不完全正确):

Or in VB.NET (might not be completely syntactically correct):

<XmlRoot ("foo")> _
Public Class Foo
     <XmlAttribute ("bar")>_
     Public bar As String
     <XmlAttribute ("baz")>_
     Public baz As String
End Class

然后您可以使用 XmlSerializer 类输出 XML.

You can then use the XmlSerializer class to output XML.

在 C# 中:

using(XmlSerializer xmls = new XmlSerializer(typeof(Foo)){
    TextWriter tw = new StreamWriter( "foo.xml" );
    //use it!
}

或VB:

Using xmls As New XmlSerializer(gettype(Foo)), _
    tw As TextWriter = New StreamWriter("foo.xml")

    ''//use it!
End Using

参考.

这篇关于如何在 VB.NET 中编写易于 XML 序列化的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆