序列化(和反序列化)XML列表
本文关键字:XML 列表 反序列化 序列化 | 更新日期: 2023-09-27 18:13:29
我在序列化一些c#字段到XML文件时遇到了一些问题。下面是我的代码:
public class Facility
{
public string ID = "";
public string Name = "";
public List<Profile> Profiles { get; set; }
}
public class PrefSet
{
public string SomeItem = "";
public string AnotherItem = "";
}
public class Config
{
public string Username = "";
public string Password = "";
public List<Facility> Facilities { get; set; }
public static void SerializeObjectToFile<T>(T dataToSerialize, string filePath)
{
try
{
using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
writer.Formatting = Formatting.Indented;
serializer.Serialize(writer, dataToSerialize);
writer.Close();
}
}
catch
{
File.Create(filePath);
}
}
public static T DeserializeObjectFromFile<T>(string filePath)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
T serializedData;
using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
serializedData = (T)serializer.Deserialize(stream);
}
return serializedData;
}
catch
{
throw;
}
}
}
我想配置它,这样我将有一个这样的XML输出:
<?xml version="1.0" encoding="Windows-1252"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Username>admin</Name>
<Password>123456</VoiceServer>
<Facilities>
<Facility>
<ID>1</ID>
<Name>First Facility</Name>
<Profiles>
<Profile>
<SomeItem>Value</SomeItem>
<AnotherItem>Value</AnotherItem>
</Profile>
<Profile>
<SomeItem>Value</SomeItem>
<AnotherItem>Value</AnotherItem>
</Profile>
<Profile>
<SomeItem>Value</SomeItem>
<AnotherItem>Value</AnotherItem>
</Profile>
</Profiles>
</Facility>
<Facility>
<ID>2</ID>
<Name>Second Facility</Name>
<Profiles>
<Profile>
<SomeItem>Value</SomeItem>
<AnotherItem>Value</AnotherItem>
</Profile>
<Profile>
<SomeItem>Value</SomeItem>
<AnotherItem>Value</AnotherItem>
</Profile>
<Profile>
<SomeItem>Value</SomeItem>
<AnotherItem>Value</AnotherItem>
</Profile>
</Profiles>
</Facility>
</Facilities>
</Config>
注意可以有多个Profile和Facility列表。
下面是我用来执行序列化的代码:
Config config = new Config();
Facility fac = new Facility();
Profile prof = new Profile();
if (File.Exists(CONFIG_FILE)) config = Config.DeserializeObjectFromFile<Config>(CONFIG_FILE);
fac.ID = "1";
fac.Name = "Facility One";
prof.SomeItem = "Value";
prof.AnotherItem = "Value";
config.Facilities.Add(fac);
fac.Profiles.Add(prof);
Config.SerializeObjectToFile<Config>(config, CONFIG_FILE);
另外,例如,我希望能够编辑和保存对项目的更改。
我遇到的问题是,它将创建XML格式,但如果我改变一个值,它将创建一个全新的Facility项,而不是更新现有的Facility列表项。
你的可序列化对象中的属性必须是public属性,如
public string Username { get; set; }
那么你可以使用[xml]方面在你的类
中构建你的xml结构。例子 [xmlignore]
用于您不想序列化的内容,例如方法和函数
[xmlnode("Username")]
public string Username { get; set; }
还有更多。您可以查看有关XML序列化的Microsoft文档来了解所有这些。
您可能还必须将[serializable]
方面放在类的顶部。