如何使用XML存储一个简单的对象(C#)

时间:2009-10-06 04:41:47

标签: c# xml

我一直在使用以下文件来保存数据:

field1 field2 field3 field4
myname myhashedpass myemail@email.com more stuff after
etc etc etc etc

每一行都被转换为字符串(姓名,通行证,电子邮件)

我想将我的文本文件(见上文)转换为XML文件,如下所示:

<person1>
   <name>myname</name>
   <pass>myhashedpass</pass>
   <email>etc</email>
</person1>

<person2>
etc etc etc etc

基本上,我坚持如何进行迁移,并且操作XML数据的方式与处理文本数据的方式相同

5 个答案:

答案 0 :(得分:7)

对你问题的回答是:

using System;
using System.Linq;
using System.Xml.Linq;

namespace XmlSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            var person1 = new Person();
            person1.Name = "Joe";
            person1.Password = "Cla$$ified";
            person1.Email = "none@your.bussiness";

            var person2 = new Person();
            person2.Name = "Doe";
            person2.Name = "$ecret";
            person2.Email = "dont@spam.me";

            var persons = new[] {person1, person2};

            XElement xml = new XElement("persons",
                                        from person in persons
                                        select new XElement("person",
                                                            new XElement("name", person.Name),
                                                            new XElement("password", person.Password),
                                                            new XElement("email", person.Email))
                                        );
            xml.Save("persons.xml");

            XElement restored_xml = XElement.Load("persons.xml");
            Person[] restored_persons = (from person in restored_xml.Elements("person")
                                         select new Person
                                                    {
                                                        Name = (string)person.Element("name"),
                                                        Password = (string)person.Element("password"),
                                                        Email = (string)person.Element("email")
                                                    })
                                        .ToArray();
            foreach (var person in restored_persons)
            {
                Console.WriteLine(person.ToString());
            }
            Console.ReadLine();
    }
}

public class Person
{
    public string Name { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public override string ToString()
    {
        return string.Format("The person with name {0} has password {1} and email {2}",
                             this.Name, this.Password, this.Email);
    }
}

}

但是,让内置的serializattion类为您进行XML的转换更好。下面的代码需要显式引用System.Runtime.Serialization.dll。使用声明本身是不够的:

using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.Serialization;

namespace XmlSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            var person1 = new Person();
            person1.Name = "Joe";
            person1.Password = "Cla$$ified";
            person1.Email = "none@your.bussiness";

            var person2 = new Person();
            person2.Name = "Doe";
            person2.Name = "$ecret";
            person2.Email = "dont@spam.me";

            var persons = new[] {person1, person2};

            DataContractSerializer serializer=new DataContractSerializer(typeof(Person[]));
            using (var stream = new FileStream("persons.xml", FileMode.Create, FileAccess.Write))
            {
                serializer.WriteObject(stream,persons);
            }

            Person[] restored_persons;
            using (var another_stream=new FileStream("persons.xml",FileMode.Open,FileAccess.Read))
            {
                restored_persons = serializer.ReadObject(another_stream) as Person[];
            }

            foreach (var person in restored_persons)
            {
                Console.WriteLine(person.ToString());
            }
            Console.ReadLine();
        }
    }

    [DataContract]
    public class Person
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Password { get; set; }
        [DataMember]
        public string Email { get; set; }
        public override string ToString()
        {
            return string.Format("The person with name {0} has password {1} and email {2}",
                                 this.Name, this.Password, this.Email);
        }
    }
}

答案 1 :(得分:4)

所以要读出你的原始文件,你有类似的东西:

var people = File.ReadAllLines("filename"))
    .Select(line => { 
       var parts = line.Split();
       return new Person { 
           Name = parts[0],
           Password = parts[1],
           Email = parts[2]
       });

然后您可以通过以下方式写出xml:

var serializer = new XmlSerializer(typeof(Person));
var xmlfile = File.OpenWrite("somefile");
foreach(var person in people)
    serializer.Serialize(person, xmlfile);

答案 2 :(得分:1)

您可能需要查看此XML Serialization tutorial。序列化可以为您节省大量加载和保存XML文件的工作。

答案 3 :(得分:1)

Linq提供了一种使用XNode构建XML的好方法:

from p in person
  select new XElement("person",
    from s in p.Keys
      select new XElement(s, p[s]));

容易成为蛋糕。

答案 4 :(得分:1)

从您的问题来看并不完全清楚,但听起来您将Person类序列化为文本文件。这可能是XmlSerializer的完美用例。

示例代码:

class Person
{
    // XmlSerializer requires parameterless constructor
    public Person()
    {
    }

    public string Name { get; set; }

    public string Pass { get; set; }

    public string Email { get; set; }

    public string Host { get; set; }
}

// ...

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

// Write a person to an XML file
Person person = new Person() { Name = "N", Pass = "P", Email = "E", Host = "H" };
using (XmlWriter writer = XmlWriter.Create("person.xml"))
{
    serializer.Serialize(writer);
}

// Read a person from an XML file
using (XmlReader reader = XmlReader.Create("person.xml"))
{
    person = (Person)serializer.Deserialize(reader);
}