xml文件读写

写入

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);

读取

List<ColumnDto> columns = new List<ColumnDto>();
//将XML文件加载进来
XDocument document = XDocument.Load(filePath);
//获取到XML的根元素进行操作
XElement root = document.Root;
//获取根元素下的所有子元素
IEnumerable<XElement> enumerable = 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; }
}

获得结果

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Column>
    <Name>Time</Name>
    <AliasName>时间</AliasName>
    <IsCanNotModify>false</IsCanNotModify>
  </Column>
</Root>

示例代码

ReadAndWriteXmlDemo

posted @ 2020-04-25 19:58  Lulus  阅读(719)  评论(2编辑  收藏  举报