Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use XML serialization to serialize a collection without the parent node

Tags:

Let's say I have a class;

public class Car  {    public List<Passenger> Passengers {get; set;}  } 

I want to serialize this to XML such that Passengers are child nodes of Car and there is no intervening Passengers node. In other words I want the output to look like this;

<Car>   <Passenger>...</Passenger>   <Passenger>...</Passenger> </Car> 

and not like this, which is the default layout;

<Car>      <Passengers>     <Passenger>...</Passenger>     <Passenger>...</Passenger>   </Passengers>  </Car> 

There's an attribute I need to add to Car.Passengers to achieve this, I don't recall which though.

like image 353
Stuart Hallows Avatar asked Mar 12 '09 16:03

Stuart Hallows


People also ask

What is the correct way of using XML serialization?

XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.

What is the basic difference between SOAP serialization and XML serialization?

XML serialization can also be used to serialize objects into XML streams that conform to the SOAP specification. SOAP is a protocol based on XML, designed specifically to transport procedure calls using XML. To serialize or deserialize objects, use the XmlSerializer class.

What is XML serialization and what is the purpose of using it?

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.

Which class should be used to serialize an object in XML format?

Xml. Serialization namespace) class is used to serialize and deserialize. The class method Serialize is called. Since we have to serialize in a file, we create a " TextWriter ".


1 Answers

This is what I was after!

[XmlElement("Passenger")] public List<Passenger> Passengers {get; set;} 
like image 101
Stuart Hallows Avatar answered Sep 18 '22 12:09

Stuart Hallows