views:

23

answers:

1

I'm serialising a List of a class and I'm not happy about the generated XML output.

[Serializable()]
public class Foo
{

    [XmlAttribute]
    public String Property1 { get; set; }

    public Foo() { }
}

public class Foo2
{
   List<Foo> _list = new List<Foo>()
   {
      new Foo(){ Property1="hello"}
    };

   // ...
   // code for serialization
   string path = "asdasd";
   using (FileStream fs = new FileStream(path, FileMode.Create))
   {
     XmlSerializer xs = new XmlSerializer(typeof(List<Foo>));
     xs.Serialize(fs, _list);
     fs.Close();
   }
}

The output will result in:

<?xml version="1.0"?>
<ArrayOfFoo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <Foo Property1="hello" />
</ArrayOfFoo>

Where must I set which attribute to alter the name of ArrayOfFoo?

+2  A: 

Just use the proper constructor:

var xs = new XmlSerializer(typeof(List<Foo>), new XmlRootAttribute("foos"));

Also you could safely remove the [Serializable] attribute from your Foo class. This is for binary serialization and XmlSerializer ignores.

Darin Dimitrov
thank you, worked
citronas