是否可以将XML反序列化为List <t>?</t>

时间:2009-03-03 20:47:46

标签: c# serialization xml-serialization xml-deserialization

给出以下XML:

<?xml version="1.0"?>
<user_list>
   <user>
      <id>1</id>
      <name>Joe</name>
   </user>
   <user>
      <id>2</id>
      <name>John</name>
   </user>
</user_list>

以下课程:

public class User {
   [XmlElement("id")]
   public Int32 Id { get; set; }

   [XmlElement("name")]
   public String Name { get; set; }
}

是否可以使用XmlSerializer将xml反序列化为List<User>?如果是这样,我需要使用哪种类型的附加属性,或者我需要使用哪些其他参数来构建XmlSerializer实例?

如果不太优选,可以接受数组(User[])。

7 个答案:

答案 0 :(得分:130)

您可以封装列表:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

[XmlRoot("user_list")]
public class UserList
{
    public UserList() {Items = new List<User>();}
    [XmlElement("user")]
    public List<User> Items {get;set;}
}
public class User
{
    [XmlElement("id")]
    public Int32 Id { get; set; }

    [XmlElement("name")]
    public String Name { get; set; }
}

static class Program
{
    static void Main()
    {
        XmlSerializer ser= new XmlSerializer(typeof(UserList));
        UserList list = new UserList();
        list.Items.Add(new User { Id = 1, Name = "abc"});
        list.Items.Add(new User { Id = 2, Name = "def"});
        list.Items.Add(new User { Id = 3, Name = "ghi"});
        ser.Serialize(Console.Out, list);
    }
}

答案 1 :(得分:41)

如果您使用User装饰XmlType课程以匹配所需的大写字母:

[XmlType("user")]
public class User
{
   ...
}

然后XmlRootAttribute ctor上的XmlSerializer可以提供所需的根,并允许直接读入List&lt;&gt;:

    // e.g. my test to create a file
    using (var writer = new FileStream("users.xml", FileMode.Create))
    {
        XmlSerializer ser = new XmlSerializer(typeof(List<User>),  
            new XmlRootAttribute("user_list"));
        List<User> list = new List<User>();
        list.Add(new User { Id = 1, Name = "Joe" });
        list.Add(new User { Id = 2, Name = "John" });
        list.Add(new User { Id = 3, Name = "June" });
        ser.Serialize(writer, list);
    }

...

    // read file
    List<User> users;
    using (var reader = new StreamReader("users.xml"))
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<User>),  
            new XmlRootAttribute("user_list"));
        users = (List<User>)deserializer.Deserialize(reader);
    }

信用:基于answerYK1

答案 2 :(得分:16)

我想我找到了一个更好的方法。您不必将属性放入类中。我已经为序列化和反序列化制作了两种方法,它们将通用列表作为参数。

看看(对我有用):

private void SerializeParams<T>(XDocument doc, List<T> paramList)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType());

        System.Xml.XmlWriter writer = doc.CreateWriter();

        serializer.Serialize(writer, paramList);

        writer.Close();           
    }

private List<T> DeserializeParams<T>(XDocument doc)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));

        System.Xml.XmlReader reader = doc.CreateReader();

        List<T> result = (List<T>)serializer.Deserialize(reader);
        reader.Close();

        return result;
    }

所以你可以序列化你想要的任何列表!您不需要每次都指定列表类型。

        List<AssemblyBO> list = new List<AssemblyBO>();
        list.Add(new AssemblyBO());
        list.Add(new AssemblyBO() { DisplayName = "Try", Identifier = "243242" });
        XDocument doc = new XDocument();
        SerializeParams<T>(doc, list);
        List<AssemblyBO> newList = DeserializeParams<AssemblyBO>(doc);

答案 3 :(得分:15)

是的,它会序列化和反序列化List&lt;&gt;。如果有疑问,请确保使用[XmlArray]属性。

[Serializable]
public class A
{
    [XmlArray]
    public List<string> strings;
}

这适用于Serialize()和Deserialize()。

答案 4 :(得分:7)

是的,它确实反序列化为List&lt;&gt;。无需将其保留在数组中并将其封装/封装在列表中。

public class UserHolder
{
    private List<User> users = null;

    public UserHolder()
    {
    }

    [XmlElement("user")]
    public List<User> Users
    {
        get { return users; }
        set { users = value; }
    }
}

反序列化代码,

XmlSerializer xs = new XmlSerializer(typeof(UserHolder));
UserHolder uh = (UserHolder)xs.Deserialize(new StringReader(str));

答案 5 :(得分:4)

不确定List&lt; T&gt;但阵列当然可行。而一点点魔法使得再次进入List非常容易。

public class UserHolder {
   [XmlElement("list")]
   public User[] Users { get; set; }

   [XmlIgnore]
   public List<User> UserList { get { return new List<User>(Users); } }
}

答案 6 :(得分:2)

怎么样

XmlSerializer xs = new XmlSerializer(typeof(user[]));
using (Stream ins = File.Open(@"c:\some.xml", FileMode.Open))
foreach (user o in (user[])xs.Deserialize(ins))
   userList.Add(o);    

不是特别花哨,但它应该有效。