Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize class to XML?

I have the follow class and the list that holds it:

public class Transport
{
    public string TransportType { get; set; }
    public string Mode { get; set; }
    public class Coordinates
    {
        public float ID { get; set; }
        public float LocX { get; set; }
        public float LocY { get; set; }
        public float LocZ { get; set; }
        public ObjectState State { get; set; }
        public List<int[]> Connections = new <int[]>();
    }
}

public enum ObjectState
{
    Fly,
    Ground,
    Water
}

public static List<Transport> Tracking = new List<Transport>();

How do I serialize the Tracking to XML ?

I know I can use [Serializable] on the list and serialize it to file but I am not sure on how I define it to be saved as XML.

like image 974
Guapo Avatar asked May 09 '11 13:05

Guapo


People also ask

What is serialization of XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

Why do we use XML serializer class?

With the XmlSerializer you can take advantage of working with strongly typed classes and still have the flexibility of XML. Using fields or properties of type XmlElement, XmlAttribute or XmlNode in your strongly typed classes, you can read parts of the XML document directly into XML objects.

What is serialization XML Java?

Serialization transforms a Java object or graph of Java object into an array of bytes which can be stored in a file or transmitted over a network. It is a crucial concept to learn for earning your Java certification. At a later time we can transform those bytes back into Java objects.


1 Answers

If both of your classes were tagged with the [Serializable] attribute, then saving things to a file should be as simple as:

var serializer = new XmlSerializer(typeof(Transport));

using(var writer = new StreamWriter("C:\\Path\\To\\File.xml"))
{
    serializer.Serialize(writer, instance);
}

Update

Sorry, didn't realize you were asking about how to customize the output. That is what the [XmlAttribute] and [XmlElement] attributes are for:

public class Transport
{
    // Store TransportType as an attrribute called Type in the XML
    [XmlAttribute("Type")]
    public string TransportType { get; set; }

    // Rest of Implementation
}
like image 164
Justin Niessner Avatar answered Oct 14 '22 16:10

Justin Niessner