错误反序列化XML

时间:2014-01-15 05:47:37

标签: c# xml deserialization xml-deserialization

我在C#

中反序列化XML时出错
        public static void Main (string[] args)
        {
            String content;
            content = "<Users><User><postedBy>Bob</postedBy><name>1</name></User><User><postedBy>Bob2</postedBy><name>2</name></User></Users>";
            TextReader reader = new StringReader (content);
            XmlSerializer s = new XmlSerializer (typeof(User));
            List<User> r = (List<User>)s.Deserialize (reader);
            int i =0;
            foreach(User user in r)
            {
                Console.WriteLine (r[i]);
                i++;
            }
        }


    }

    public class User
    {
        [XmlElement(ElementName = "postedBy")]
        public string PostedBy { get; set; }
        [XmlElement(ElementName = "name")]
        public string name { get; set; }
    }

enter image description here

1 个答案:

答案 0 :(得分:1)

创建另一个类来处理根元素:

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

并反序列化为typeof(Users)

XmlSerializer s = new XmlSerializer(typeof(Users));
Users r = (Users)s.Deserialize(reader);

然后,您可以User

访问所有r.users元素