實體類與XML序列化與反序列化

.Net菜鸟站發表於2024-05-05

///


/// 實體類序列化為Xml
///

///
public void SerializeXml(List slave)
{
XmlSerializer serializer = new XmlSerializer(typeof(List));
using (StringWriter textWriter = new StringWriter())
{
serializer.Serialize(textWriter, slave);
string xmlContent = textWriter.ToString();
// 這裡可以將xmlContent儲存到檔案
}
}

///


/// Xml反序列化為實體類
///

///
///
///
public List DeserializeEntity(string xmlName)
{
// 獲取應用程式根目錄下的XML檔案路徑
string xmlFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlName);
// 建立XmlSerializer物件
XmlSerializer serializer = new XmlSerializer(typeof(List));
// 反序列化XML檔案到List
using (StreamReader reader = new StreamReader(xmlFilePath))
{
return (List)serializer.Deserialize(reader);
}
}

相關文章