开发者

How to change the name of a collection of a custom class upon XML serialization?

开发者 https://www.devze.com 2023-01-09 14:32 出处:网络
I\'m serialising a List of a class and I\'m not happy about the generated XML output. [Serializable()]

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 fo开发者_运维技巧r 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">
  <Foo Property1="hello" />
</ArrayOfFoo>

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消