C# 读取xml文档并传值给公共类属性
Publicfile publicfile = new Publicfile(); try { string filePath = Path.Combine("C:?", fileName); if (!File.Exists(filePath)) { WriteErrorLog($"File({fileName}) not exists."); return blockvmProfile; } Type type = typeof(Publicfile); PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); XDocument xDoc = XDocument.Load(filePath); var configItems = from sc in xDoc.Descendants("section") select new { Name = sc.Element("NAME")?.Value, Value = sc.Element("VALUE")?.Value }; foreach (var item in configItems) { foreach (PropertyInfo property in properties) { if (item.Name == property.Name) { object value; if (property.PropertyType == typeof(string)) { value = item.Value; } else if (property.PropertyType == typeof(int)) { value = int.Parse(item.Value); } else if (property.PropertyType == typeof(float)) { value = float.Parse(item.Value); } else { value = null; } property.SetValue(publicfile, value); break; } } } } catch (Exception ex) { WriteErrorLog($"Get file({fileName}) failed." + ex.ToString()); }