How do I write objects for easy XML Serialization in VB.NET?

北慕城南 提交于 2019-12-18 07:06:34

问题


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?


回答1:


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.

For example (in C#):

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

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

You can then use the XmlSerializer class to output XML.

In C#:

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

Or VB:

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

    ''//use it!
End Using

Reference.




回答2:


Since you asked about making it 'easy', then there are three rules to follow that will help keeps things very simple:

  1. Only use property types that are serializable
  2. Don't use collections or arrays as properties that need to be serialized
  3. Don't have properties with "bad" side-effects. By 'bad', I mostly mean two public properties that are backed by the same underlying private field.

Note that if you break these rules you can probably still serialize your class, but it's likely to be a lot more work.

For item #2, a quick fix is using a datatable or dataset, since those are serializable.




回答3:


To go with a simple 'save' feature either use the .net xml serialization [1] or create yourself a n in memory DateSet to persist the 'state of the world' in as many DateTables as your see fit. It rather depends how complext your object model that you are trying to persist is.

[1] simplest example I could find quickly (C#, sorry but you'll get the gist) http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm



来源:https://stackoverflow.com/questions/223526/how-do-i-write-objects-for-easy-xml-serialization-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!