XMLSerialization

本文关键字:XMLSerialization | 更新日期: 2023-09-27 17:49:56

如何序列化/反序列化以下内容

<<p> 反应/strong>
<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;}
}

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

XMLSerialization

您的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()代替通常的新User{},它接受"字段"列表并返回User

对象

试试这样

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