XML序列化类型的数组="阵"在.NET [英] XML serializing arrays with type="array" in .NET

查看:179
本文介绍了XML序列化类型的数组="阵"在.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图类序列化到XML的,但我对输出一些严格的要求(因为我想Rails的的ActiveResource来使用它)。其中的一个要求,是专门用于数组的。这里有两个例子:

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>

反正是有欺骗的XmlSerializer到产生这一产出?

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

推荐答案

您也可以看看的控制XML序列化使用属性的。

这样的事情可能会为你工作。

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);

这篇关于XML序列化类型的数组=&QUOT;阵&QUOT;在.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆