XML序列化

XMLSerialization

如何serialize/deserialize以下

响应

<xml>
 <record type="user">
  <field name="userId" value="Id1"/>
  <field name="userName" value="Name1"/>
  <field name="userStreet" value="Street1"/>
  <field name="userCountry" value="Country1"/>
 </record>
 <record type="user">
  <field name="userId" value="Id2"/>
  <field name="userName" value="Name2"/>
  <field name="userStreet" value="Street2"/>
  <field name="userCountry" value="Country2"/>
 </record>
</xml>

User.cs

class User
{
 public int UserId{get;set;}
 public string UserName{get;set;}
 public string UserStreet{get;set;}
 public string UserCountry{get;set;}
}

我不知道从哪里开始,因为我还没有遇到过这样的响应结构。

尝试这样的事情

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"C:\temp\test.xml";
        static void Main(string[] args)
        {
            Root root = new Root()
            {
                records = new List<Record>(){
                    new Record(){
                        type = "user",
                        fields = new List<Field>(){
                            new Field() { name= "userId",  value = "Id1"},
                            new Field() { name= "userName", value = "Name1"},
                            new Field() { name="userStreet", value = "Street1"},
                            new Field() { name="userCountry", value="Country1"}
                        }
                    },
                    new Record(){
                        type = "user",
                        fields = new List<Field>(){
                            new Field() { name = "userId", value="Id2"},
                            new Field() { name = "userName", value="Name2"},
                            new Field() { name= "userStreet", value="Street2"},
                            new Field() { name="userCountry", value="Country2"}
                        }
                    }
                }
            };


            XmlSerializer serializer = new XmlSerializer(typeof(Root));

            StreamWriter writer = new StreamWriter(FILENAME);
            XmlSerializerNamespaces _ns = new XmlSerializerNamespaces();
            _ns.Add("", "");
            serializer.Serialize(writer, root, _ns);
            writer.Flush();
            writer.Close();
            writer.Dispose();



            XmlSerializer xs = new XmlSerializer(typeof(Root));
            XmlTextReader reader = new XmlTextReader(FILENAME);
            Root  newRoot = (Root)xs.Deserialize(reader);

            List<User> users = new List<User>();
            foreach (Record record in newRoot.records.AsEnumerable())
            {
                User newUser = new User();
                users.Add(newUser);
                foreach (Field field in record.fields)
                {
                    switch (field.name)
                    {
                        case "userId" :
                            newUser.UserId = field.value;
                            break;
                        case "userName":
                            newUser.UserName  = field.value;
                            break;
                        case "userStreet":
                            newUser.UserStreet = field.value;
                            break;
                        case "userCountry":
                            newUser.UserCountry = field.value;
                            break;
                    }
                }
            }



        }
    }

    [XmlRoot("Root")]
    public class Root
    {
        [XmlElement("record")]
        public List<Record> records { get; set; } 
    }
    [XmlRoot("record")]
    public class Record
    {
        [XmlAttribute("type")]
        public string type { get; set; }
        [XmlElement("field")]
        public List<Field> fields { get; set; } 
    }

    [XmlRoot("field")]
    public class Field
    {
        [XmlAttribute("name")]
        public string name { get; set; }
        [XmlAttribute("value")]
        public string value { get; set; }
    }
    class User
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public string UserStreet { get; set; }
        public string UserCountry { get; set; }
    }

}

您的 XML 不同,因为对象属性位于元素 "field" 的属性内部,而不是像

这样的元素
<xml>
 <User>
  <UserName>
    Name1
  </UserName>
 </User>
</xml>

所以我要做的是编写一个函数来像

那样为我进行解析
public static User get_user(IEnumerable<XElement> fields)
    {
        User u = new User();
        foreach (var item in fields)
        {
            String attribute = item.Attribute("name").Value;
            String val = item.Attribute("value").Value;
            if (attribute == "userName")
            {
                u.UserName = val;
            }
            else if (attribute == "userStreet")
            {
                u.UserStreet = val;
            }
            //and so on...
        }
        return u;
    }

然后像

一样使用它
//using System.Xml.Linq;
XDocument document =XDocument.Parse(string_response); //I'm assuming response is in string
List<User> users = (from xnode in document.Element("xml").Elements("record")
                            select get_user(xnode.Elements("field"))
                   ).ToList();

在 Linq 表达式中,我使用的是 get_user() 而不是通常的 new User{},它获取 User[= 的 "fields" 和 returns 对象的列表13=]