5

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?

Robert Strauch
  • 12,055
  • 24
  • 120
  • 192
  • see [this](http://stackoverflow.com/questions/3303165/using-xmlarrayitem-attribute-without-xmlarray-on-serializable-c-sharp-class) answer – Jens Kloster Jun 24 '13 at 12:42

2 Answers2

4

you can try :

public class DocumentOrder {
  // ...
  [XmlAttribute]
  public string Name { get; set; }
  [XmlElement("Document")]
  public List<Document> Documents { get; set; }
}
Joffrey Kern
  • 6,449
  • 3
  • 25
  • 25
1

Should just be a case of:

public class DocumentOrder {
  // ...
  [XmlAttribute]
  public string Name { get; set; }

  [XmlArrayItem("Document")]
  public List<Document> Documents { get; set; }
}

There are some good examples on MSDN on what the various XML serialization attributes do

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166