c# 实现数据实体类转xml 辅助方法类

编程开发 xml转Entity帮助类

新实现传送门=> C#实现实体类和XML文件转换

以下代码相较于上方的方法的实用参考价值相对较低 建议前往上方链接查看新的方式

/// <summary>
/// XML实体映射处理类
/// </summary>
/// <typeparam name="T">不支持多层嵌套类型</typeparam>
public sealed class XmlHelper<T> : EntityFeatures<T> where T : new()
{
List<ColumnAttribute> PropertyFeaturesSet
{
get
{
return this.ColumnFeaturesSet();
}
}

TableAttribute XmlRoot
{
get
{
return this.TableFeatures();
}
}

/// <summary>
/// 保存为xml文件
/// </summary>
/// <param name="XmlUri">xml文件地址</param>
/// <param name="DataModel"></param>
public bool Save(string XmlUri, T DataModel)
{
if (string.IsNullOrEmpty(XmlRoot.Name) || PropertyFeaturesSet.Count <= 0) return false;
XElement Root = new XElement(XmlRoot.Name);
Root.SetAttributeValue("Title", XmlRoot.Title);

XDocument EntityXML = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), Root);///创建一个
PropertyFeaturesSet.ForEach(data =>
{
XElement element = new XElement(data.Property.Name, data.PropertyValue<T>(DataModel));
element.SetAttributeValue("Title", data.Title);
EntityXML.Root.Add(element);
});

EntityXML.Save(XmlUri);
return true;
}

/// <summary>
/// 读取xml文件转换为泛型
/// </summary>
/// <param name="XmlUri">xml文件地址</param>
/// <returns></returns>
public T Read(string XmlUri)
{
if (string.IsNullOrEmpty(XmlRoot.Name) || PropertyFeaturesSet.Count <= 0) return default(T);

using (FileStream fs = new FileStream(XmlUri, FileMode.Open, FileAccess.Read))
{
XmlDocument EntityXML = new XmlDocument();///创建一个
EntityXML.Load(fs);

T TEntity = new T();
foreach (XmlNode node in EntityXML.SelectSingleNode("/" + XmlRoot.Name))
{
Type FeaturesType = typeof(T);
PropertyInfo[] pArray = FeaturesType.GetProperties();
foreach (PropertyInfo p in pArray)
{
PropertyFeaturesSet.SingleOrDefault(data =>
{
if (p.Name != data.Property?.Name || !p.CanWrite || !node.Name.Equals(data.Property.Name)) return false;
if (string.IsNullOrEmpty(node.InnerText)) return false;
object value = node.InnerText;
if (FutureToolkits.MSSQL.DataConverter.PropertyTypeIsNullable(p))///判断是不是null类型
{
value = Convert.ChangeType(value, p.PropertyType.GetGenericArguments().SingleOrDefault());
}
p.SetValue(TEntity, value, null); return true;
});
}
}
fs.Close();
fs.Dispose();
return TEntity;
}
}
}



相关推荐
免责声明 本站部分内容来源于互联网公开资源分享学习交流,若其中有侵犯到了您的权益 还请邮件联系我方删除