C# 将实体转xml/xml转实体
2024-09-08 16:40:20
xml转实体
/// <summary>
/// 把xml转换成实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="xmlString"></param>
/// <returns></returns>
public static List<T> GetXmlModel<T>(T model, string xmlString) where T : class
{
List<T> list = new List<T>();
try
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlString);//把xml格式的字符串转为XMLDataDocument对象
XmlNodeList data = xml.DocumentElement.ChildNodes;//得到的是xml对象的节点数组
foreach (XmlNode item in data)
{
Dictionary<string, string> xmlDic = new Dictionary<string, string>();
if (item.ChildNodes.Count > 0)
{
foreach (XmlNode it in item.ChildNodes)
{
xmlDic.Add(it.LocalName, it.InnerText);
}
}
var m = model.GetType();
foreach (PropertyInfo p in m.GetProperties())
{
string name = p.Name;
if (xmlDic.Keys.Contains(name))
{
string value = xmlDic.Where(x => x.Key == name).FirstOrDefault().Value;
p.SetValue(model,
string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, p.PropertyType), null);
}
}
list.Add(model);
}
return list;
}
catch (Exception ex)
{
return list;
}
}
实体转xml
/// <summary>
/// 地图文件 - 实体转xml
/// </summary>
/// <param name="patrolEquipmentDto"></param>
/// <param name="path"></param>
private static void MapFileToXmlMethod(List<LinkageConfigFileDto> patrolEquipmentDto, string path)
{
XmlDocument xmlDoc = new XmlDocument();
//加入XML的声明段落,Save方法不再xml上写出独立属性
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
//加入根元素 XmlElement root = xmlDoc.CreateElement("Effect_Config");
xmlDoc.AppendChild(root); foreach (var item in patrolEquipmentDto)
{
XmlElement memberlist = xmlDoc.CreateElement("Item");
XmlElement source_code = xmlDoc.CreateElement("source_code");
source_code.InnerText = item?.source_code; XmlElement source_name = xmlDoc.CreateElement("source_name");
source_name.InnerText = item?.source_name; XmlElement source_type = xmlDoc.CreateElement("source_type");
source_type.InnerText = item?.source_type; XmlElement device_id = xmlDoc.CreateElement("device_id");
device_id.InnerText = item?.device_id; memberlist.AppendChild(source_code);
memberlist.AppendChild(source_name);
memberlist.AppendChild(source_type);
memberlist.AppendChild(device_id);
root.AppendChild(memberlist);
}
xmlDoc.Save(path);
}
最新文章
- 应用程序框架实战三十四:数据传输对象(DTO)介绍及各类型实体比较
- C#实现对远程服务器的内存和CPU监控
- linux下用户账户切换
- H5前端面试题及答案(1)
- poj3207 2-SAT入门
- 软件工程第一次个人项目——词频统计by11061153柴泽华
- memcahced 更新
- Nginx+uWSGI+Django+Python在Linux上的部署
- 合(析)取范式转主合(析)取范式--》Java实现
- [Android]android.graphics.Camera实现图像的旋转、缩放,配合Matrix实现图像的倾斜
- UWP: 体验应用内购新接口——StoreContext类
- Python 动态导入模块
- Python03(Linux和Python简介)
- metasploit渗透测试魔鬼训练营环境
- Cookie的使用(14)
- 【HDU3032】Nim or not Nim?(博弈论)
- Java OOM 常见情况
- C#6.0新特性:var s = $";{12}+{23}={12+23}";
- browser.versions.weixin
- C# 中的动态创建技术