How to write objects for simple XML serialization in VB.NET?

I am writing a small application in VB.NET, and I would like some of the classes to be able to write themselves in XML to serve as a save function. I saw XSD files used to generate VB classes that can very easily be serialized to and from XML. How would I do this if I have any pre-existing XML format that I will need to conform to since I just create the classes myself?

+3
source share
3 answers

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

For example (in C #):

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

VB.NET( , ):

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

XmlSerializer XML.

#:

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

.

+6

, "", , :

  • ,
  • ,
  • "" . "", , .

, , , , , , , .

№ 2 , .

+2

To go with the simple “save” function, either use the serialization of .net xml [1] or create n for yourself in the DateSet memory to save the “state of the world” for as many DateTables as you like. It rather depends on how complemented your object model you are trying to save.

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

0
source

Source: https://habr.com/ru/post/1698543/


All Articles