XML serializing arrays with type=“array” in .NET

我的未来我决定 提交于 2019-12-11 12:49:17

问题


I'm attempting to serialize a class to XML, but I have some strict requirements on the output (because I want Rails' ActiveResource to consume it). One of those requirements is specifically for arrays. Here's two examples:

class Person { public string FirstName { get; set; } }

List<Person> people = new List<Person>();
people.Add( new Person {...} );
people.Add( new Person {...} );

If I serialize the people list, I need this output:

<People type="array">
  <Person>
    <FirstName>blah</FirstName>
  </Person>
  <Person>...</Person>
</People>

Another example is like this:

class Person
{
  public string FirstName { get; set; }
  public List<Address> Addresses { get; set; }
}

class Address
{
  public string Line1 { get; set; }
}

If a serialize a person, I need this output:

<Person>
  <FirstName>blah</FirstName>
  <Addresses type="array">
    <Address>...</Address>
  </Addresses>
</Person>

Is there anyway to trick the XmlSerializer into producing this output?


回答1:


You can also take a look at Controlling XML Serialization Using Attributes.

Something like this may work for you

[XmlRoot(ElementName="People")]
public class PeopleType
{
    [XmlElement(ElementName="Person")]
    public List<Person> people  = new List<Person>()
    {
        new Person { FirstName = "Bob" },
        new Person { FirstName = "Sally" }
    };

    [XmlAttribute]
    public string type = "array";
}

PeopleType p = new PeopleType();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer xs = new XmlSerializer(typeof(PeopleType));
using (StreamWriter sw = new StreamWriter("out.xml", false))
    xs.Serialize(sw, p, ns);


来源:https://stackoverflow.com/questions/2211859/xml-serializing-arrays-with-type-array-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!