1

I'm trying to serialize an object with an attribute on the root element (which is a collection).

[XmlType("Person")]
public class Person
{
    public id Id { get; set; }
    public string Name { get; set; }
}

[XmlType("Persons")]
public class Persons : Collection<Person>
{
    [XmlAttribute("Nb")]
    public int Nb
        get {
            return this.Count;
        }
        set { }
    }
}

var persons = new Persons();
var person = new Person();
person.Id = 42;
person.Name = "Toto";
persons.Add(person);

return persons;

The serialized output is the following:

<Persons>
    <Person>
        <Id>42</Id>
        <Name>Toto</Name>
    </Person>
</Persons>

I'm expecting

<Persons Nb="1">
    <Person>
        <Id>42</Id>
        <Name>Toto</Name>
    </Person>
</Persons>

How can I bring the Nb attribute in ?

Pierre de LESPINAY
  • 44,700
  • 57
  • 210
  • 307
  • 1
    Which serializer your are using? – Vijayanath Viswanathan Sep 11 '17 at 12:27
  • My serializer is (I believe) the default one for .net core configured in `Startup` with `.AddXmlSerializerFormatters()` – Pierre de LESPINAY Sep 11 '17 at 12:30
  • `class Persons : List` - [bad idea](https://stackoverflow.com/q/21692193/1997232). – Sinatr Sep 11 '17 at 12:32
  • Still nobody have an idea how to add my `Nb` attribute ? – Pierre de LESPINAY Sep 18 '17 at 07:57
  • ok, than I'll remove comments – ASpirin Sep 18 '17 at 09:43
  • 1
    Check also [this question](https://stackoverflow.com/questions/377486/xmlserialize-a-custom-collection-with-an-attribute) seems that is similar to your case – ASpirin Sep 18 '17 at 10:05
  • Check this in your investigations: `[XmlRoot("Persons")] public class Persons : Collection, IXmlSerializable { public int Nb => Count; public XmlSchema GetSchema() => null; public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Nb", Nb.ToString()); var personSerializer = new XmlSerializer(typeof (Person)); foreach (var person in this) { personSerializer.Serialize(writer, person); } } }` – ASpirin Sep 18 '17 at 10:30
  • Your last link fixed my issue. It's due to the fact that my root class extends a collection. – Pierre de LESPINAY Sep 18 '17 at 10:33

0 Answers0