0
我有以下型號:XML序列化 - 是否可以用這種方式序列化模型?
public class ABaseObject
{
private Guid id = Guid.NewGuid();
public ABaseObject()
{
}
public Guid ID { get { return id; } }
}
public class ADerivedObject : ABaseObject
{
public ADerivedObject()
{
}
public string Name { get; set; }
}
public class AObjectCollection<T>
{
private List<T> items = new List<T>();
public AObjectCollection()
{
}
public IEnumerable<T> Items { get { return items; } }
public void Add(T item)
{
items.Add(item);
}
public void Save(string filePath)
{
FileStream writer = new FileStream(filePath, FileMode.Create);
DataContractSerializer s = new DataContractSerializer(typeof(T));
s.WriteObject(writer, this);
writer.Close();
}
public void Load(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(T));
// Deserialize the data and read it from the instance.
T deserializedObj = (T)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
}
}
所以基本上我希望能夠做到以下幾點:
var der = new ADerivedObject();
der.Name = "Test";
var col = new AObjectCollection<ADerivedObject>();
col.Add(der);
col.Save("C:\MyCollection.xml");
...
var col2 = new AObjectCollection<ADerivedObject>();
col2.Load("C:\MyCollection.xml");
當連載它應該是這個樣子:
<Collection>
<Item>
<ID></ID>
<Name></Name>
</Item>
</Collection>
我已經玩過DataContracts和XmlSerializer,但我似乎無法找到一種方法來做到這一點。
感謝這幾乎是我想要的。 – James 2010-02-05 09:07:07
出於好奇,是否可以使用DataContracts而不是XML序列化器來實現相同的格式?經過一番研究,我發現DataContracts更快。 – James 2010-02-05 10:55:25
好吧,我能夠使用DataContracts複製這個。然而,在XML中它顯示了像
James
2010-02-05 12:54:16