【问题标题】:C# XML AnnotationsC# XML 注释
【发布时间】:2018-05-19 19:27:04
【问题描述】:

我有一个 UserData 类,我正在尝试使用 XML 进行序列化和反序列化。

问题是当我序列化时,它会创建一个新的xml文件并添加数据,但是第一个添加的数据缺少<UserData></UserData>,这是再次正确读取它所必需的。

目前我可以阅读第二部分。

是否可以在我的 UserData 类中添加某种注释,以便在将对象写入 XML 时创建 <UserData>

public class UserData
{
    private string firstName, lastName, email, phone, birthday, serialNumber;

    //Empty constructor is mandatory in order to Serialize the object
    public UserData()
    {

    }

    public UserData(string firstName, string lastName, string email, string phone, string birthday, string serialNumber)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.phone = phone;
        this.birthday = birthday;
        this.serialNumber = serialNumber;
    }

    //Getters & Setters
    [XmlElement("first_name")]
    public string FirstName { get => firstName; set => firstName = value; }

    [XmlElement("last_name")]
    public string LastName { get => lastName; set => lastName = value; }

    [XmlElement("email")]
    public string Email { get => email; set => email = value; }

    [XmlElement("phone")]
    public string Phone { get => phone; set => phone = value; }

    [XmlElement("birthday")]
    public string Birthday { get => birthday; set => birthday = value; }

    [XmlElement("serial_number")]
    public string SerialNumber { get => serialNumber; set => serialNumber = value; }
}

当我使用 XmlSerializer 创建文件时,结果如下:

<?xml version="1.0" encoding="utf-8"?>
<UserData>
   <first_name>Test</first_name>
   <last_name>Test</last_name>
   <email>Test@Test.com</email>
   <phone>12312</phone>
   <birthday>12/6/2017 2:07:24 AM +01:00</birthday>
   <serial_number>d0c48895-0b39-467f-96fa-fd80aeef77dd</serial_number>
   <UserData>        <-------- CORRECT (BUT MISSING ABOVE)
   <first_name>Test2</first_name>
   <last_name>Test2</last_name>
   <email>Test2@test.com</email>
   <phone>2142141</phone>
   <birthday>12/6/2017 2:07:24 AM +01:00</birthday>
   <serial_number>21e478ed-8c74-4fff-8549-14facac2bb7b</serial_number>
   </UserData>        <----- CORRECT
 </UserData>

这就是我编写文件的方式。我认为问题在于我使用 LINQ 附加到文件,但使用 XmlSerializer 创建文件。而且 XmlSerializer 似乎没有添加正确的 XML 设置。

public async void WriteUserdataToXML(string filename, Type type, object obj, string firstName, string lastName, string email, string phone, string birthday, string serialID)
    {

        StorageFolder path = ApplicationData.Current.LocalFolder;

        //Check if file exists - create file if it does not.
        if (!File.Exists(path.Path + @"\" + filename + ".xml"))
        {
            await Task.Run(() =>
            {

                using (var stream = new FileStream(path.Path + @"\" + filename + ".xml", FileMode.Create))
                {
                    var xml = new XmlSerializer(type);

                    //removes name spacing
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");

                    //serializes object
                    xml.Serialize(stream, obj, ns);
                }
            });
        }


        //If the file already exists - append data to the existing file
        else
        {
            XElement xml = XElement.Load(path.Path + @"\" + filename + ".xml");

            xml.Add(
                new XElement("UserData",
                new XElement("first_name", firstName),
                new XElement("last_name", lastName),
                new XElement("email", email),
                new XElement("phone", phone),
                new XElement("birthday", birthday),
                new XElement("serial_number", serialID)
                ));

            using (var stream = new FileStream(path.Path + @"\" + filename + ".xml", FileMode.Create))
            {
                xml.Save(stream);
            }

        }

又是这样写的:

public List<UserData> ReadUserDataFromXML(string filename)
    {
        List<UserData> list = new List<UserData>();
        StorageFolder path = ApplicationData.Current.LocalFolder;
        string fullpath = path.Path + @"\" + filename + ".xml";
        XElement xml = XElement.Load(fullpath);


        list = (from data in xml.Elements("UserData")
                select new UserData()
                {
                    FirstName = (string)data.Element("first_name").Value,
                    LastName = (string)data.Element("last_name").Value,
                    Email = (string)data.Element("email").Value,
                    Phone = (string)data.Element("phone").Value,
                    Birthday = (string)data.Element("birthday").Value,
                    SerialNumber = (string)data.Element("serial_number").Value
                }).ToList();

        return list;
    }

【问题讨论】:

  • "
  • 谢谢你,Dylan,我会尽力调查的。
  • 使用这个:XElement xml = XElement.Load(path.Path + @"\" + filename + ".xml"); XElement userData = xml.Element("UserData"); userData.Element("first_name").SetElementValue = firstName);

标签: c# xml serialization deserialization


【解决方案1】:

XmlRootAttribute 有你。

[Serializable, XmlRoot("UserData")]
public class UserData
{ /*etc...*/ }

在某个地方使用一些常量以防规范发生变化或其他情况也很有用。

[Serializable, XmlRoot(UserData.RootName)]
public class UserData
{ 
  public const string RootName = "UserData";
  //etc...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-22
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多