anth
anth

Reputation: 1904

Xml serialization - collection attribute

HelIo,

This code:

[Serializable]
[XmlRoot("A")]
public class A
{
    public B B { get; set; }

    public void Save()
    {
        string settingsFilePath = string.Format("test.xml");
        XmlSerializer serializer = new XmlSerializer(typeof(A));
        TextWriter writer = new StreamWriter(settingsFilePath);
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces(new XmlQualifiedName[] { new XmlQualifiedName(string.Empty) });
        serializer.Serialize(writer, this, ns);
        writer.Close();
    }
}

.

public class B
{
    [XmlAttribute("c")]
    public string C { get; set; }

    public List<D> D { get; set; }
}

.

public class D
{
    [XmlAttribute("e")]
    public string E { get; set; }
}

.

A a = new A();
a.B = new B();
a.B.C = "c";
a.B.D = new List<D>();
D d = new D();
d.E = "e";
a.B.D.Add(d);
a.B.D.Add(d);
a.B.D.Add(d);
a.Save();

generates such xml file:

<?xml version="1.0" encoding="utf-8"?>
<A>
  <B c="c">
    <D>
      <D e="e" />
      <D e="e" />
      <D e="e" />
    </D>
  </B>
</A>

Is there any way to generate xml with such structure: ?

<?xml version="1.0" encoding="utf-8"?>
<A>
  <B c="c">
     <D e="e" />
     <D e="e" />
     <D e="e" />
  </B>
</A>

Upvotes: 2

Views: 1242

Answers (1)

erikH
erikH

Reputation: 2346

Decorate in class B

[XmlElement("D")]
public List<D> D { get; set; }

Upvotes: 5

Related Questions