Xml反序列化用XmlSerializer.Deserialize()
如何把下面的Xml文件用XmlSerializer.Deserialize()反序列化为这样的类对象:classclassA(){publicstringClassNam...
如何把下面的Xml文件用XmlSerializer.Deserialize()反序列化为这样的类对象:
class classA()
{
public string ClassName;
public Property[] properties;//Property是一个类
}
<xml>
<Class name="ClassName">
<Property>
<ID></ID>
<Type></Type>
</Property>
<Property>
<ID></ID>
<Type></Type>
</Property>
</Class> 展开
class classA()
{
public string ClassName;
public Property[] properties;//Property是一个类
}
<xml>
<Class name="ClassName">
<Property>
<ID></ID>
<Type></Type>
</Property>
<Property>
<ID></ID>
<Type></Type>
</Property>
</Class> 展开
2个回答
展开全部
把我的序列化和反序列化方法发给你吧,你替换一下下面的双引号:
#region XML相关的静态方法
/// <summary>
/// 使用XmlSerializer序列化对象
/// </summary>
/// <typeparam name=“T“>需要序列化的对象类型,必须声明[Serializable]特征</typeparam>
/// <param name=“obj“>需要序列化的对象</param>
public static string XmlSerialize<T>(T obj)
{
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(ms, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
/// <summary>
/// 使用XmlSerializer反序列化对象
/// </summary>
/// <param name=“xmlOfObject“>需要反序列化的xml字符串</param>
public static T XmlDeserialize<T>(string xmlOfObject) where T : class
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sr = new StreamWriter(ms, Encoding.UTF8))
{
sr.Write(xmlOfObject);
sr.Flush();
ms.Seek(0, SeekOrigin.Begin);
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(ms) as T;
}
}
}
#endregion
#region XML相关的静态方法
/// <summary>
/// 使用XmlSerializer序列化对象
/// </summary>
/// <typeparam name=“T“>需要序列化的对象类型,必须声明[Serializable]特征</typeparam>
/// <param name=“obj“>需要序列化的对象</param>
public static string XmlSerialize<T>(T obj)
{
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(ms, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
/// <summary>
/// 使用XmlSerializer反序列化对象
/// </summary>
/// <param name=“xmlOfObject“>需要反序列化的xml字符串</param>
public static T XmlDeserialize<T>(string xmlOfObject) where T : class
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sr = new StreamWriter(ms, Encoding.UTF8))
{
sr.Write(xmlOfObject);
sr.Flush();
ms.Seek(0, SeekOrigin.Begin);
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(ms) as T;
}
}
}
#endregion
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询