using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace HDMap.Plugins
{
public class XmlSerializeHelper
{
/// <summary>
/// 创建空的xml
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="xmlpath">xml路径</param>
/// <param name="objtype">对象</param>
/// <returns></returns>
public static bool CreateEmptyXml<T>(string xmlpath,T objtype)
{
try
{
XmlSerializer xmlserialize = new XmlSerializer(typeof(T));
FileStream filestream = new FileStream(xmlpath, FileMode.Create);
xmlserialize.Serialize(filestream, objtype);
filestream.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
/// <summary>
/// 序列化成xml
/// </summary>
/// <param name="xmlpath"></param>
/// <param name="updateinfo"></param>
public static bool SerializeToXml<T>(string xmlpath, T updateinfo)
{
try
{
XmlSerializer xmlserialize = new XmlSerializer(typeof(T));
FileStream filestream = new FileStream(xmlpath, FileMode.Create);
xmlserialize.Serialize(filestream, updateinfo);
filestream.Close();
return true;
}
catch(Exception e)
{
return false;
}
}
/// <summary>
/// 反序列化xml
/// </summary>
/// <param name="xmlpath">xml文件路径</param>
/// <returns></returns>
public static T DeserializeFromXml<T>(string xmlpath)
{
try
{
FileStream filestream = new FileStream(xmlpath, FileMode.Open);
XmlSerializer xmlserialize = new XmlSerializer(typeof(T));
T updateinfo = (T)xmlserialize.Deserialize(filestream);
filestream.Close();
return updateinfo;
}
catch(Exception e)
{
return default(T);
}
}
}
}
此处对所需生成xml的类的属性有要求
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace HDMap.Plugins.AddData
{
public class NewFeatureClass
{
public NewFeatureClass()
{
Fields = new List<NewFieldClass>();
}
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("AliasName ")]
public string AliasName { get; set; }
/// <summary>
/// 要素类型,Point为1,Polyline为2,Polygon为3,其他为0
/// </summary>
[XmlAttribute("GeometryType ")]
public int GeometryType { get; set; }
public List<NewFieldClass> Fields { get; set; }
//上面的属性,是另一个类字段,生成时会自动生成子节点
}
}