Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing List<> with XmlSerializer

I have defined the following classes.

Document.cs

public class Document {
  // ...
  [XmlAttribute]
  public string Status { get; set; }
}

DocumentOrder.cs

public class DocumentOrder {
  // ...
  [XmlAttribute]
  public string Name { get; set; }
  public List<Document> Documents { get; set; }
}

When serializing this to an XML I get:

<DocumentOrder Name="myname">
  <Documents>
    <Document Status="new"/>
    // ...
  </Documents>
</DocumentOrder>

But I would like to have it like that, i.e. be the Document elements to be children of DocumentOrder.

<DocumentOrder Name="myname">
  <Document Status="new"/>
  <Document Status="new"/>
  <Document Status="new"/>
  // The document element has other attributes to distinguish...
</DocumentOrder>

How can I do that?

like image 421
Robert Strauch Avatar asked Jun 24 '13 12:06

Robert Strauch


People also ask

Can you serialize a list of objects in C#?

Use the BinaryFormatter class. List, serialize. In C# programs we often need to read and write data from the disk. A List can be serialized—here we serialize (to a file) a List of objects.

Can I make XmlSerializer ignore the namespace on deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization.

What is the correct way of using XML serialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of the class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.


1 Answers

you can try :

public class DocumentOrder {
  // ...
  [XmlAttribute]
  public string Name { get; set; }
  [XmlElement("Document")]
  public List<Document> Documents { get; set; }
}
like image 146
Joffrey Kern Avatar answered Sep 27 '22 18:09

Joffrey Kern