写入
XDocument document = new XDocument(); XElement root = new XElement(Root); foreach(var columnDto in columns) { XElement column = new XElement(Column); column.SetElementValue(nameof(columnDto.Name), columnDto.Name); column.SetElementValue(nameof(columnDto.AliasName), columnDto.AliasName); column.SetElementValue(nameof(columnDto.IsCanNotModify), columnDto.IsCanNotModify); root.Add(column); } root.Save(filePath);
读取
Listcolumns = new List(); //将XML文件加载进来 XDocument document = XDocument.Load(filePath); //获取到XML的根元素进行操作 XElement root = document.Root; //获取根元素下的所有子元素 IEnumerableenumerable = root.Elements(); foreach (XElement column in enumerable) { ColumnDto columnDto = new ColumnDto(); foreach (XElement property in column.Elements()) { if (property.Name == nameof(columnDto.Name)) { columnDto.Name = property.Value; } else if(property.Name == nameof(columnDto.AliasName)) { columnDto.AliasName = property.Value; } else if (property.Name == nameof(columnDto.IsCanNotModify)) { columnDto.IsCanNotModify = bool.Parse(property.Value); } //Console.WriteLine($"{property.Name}:{property.Value}"); } columns.Add(columnDto); //Console.WriteLine(column.Attribute("id").Value); } return columns;
ColumnDto
public class ColumnDto { public string Name { get; set; } public string AliasName { get; set; } public bool IsCanNotModify { get; set; } }
获得结果
Time时间false