其他分享
首页 > 其他分享> > xml文件读写

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

标签:xml,文件,nameof,Name,column,读写,XElement,property,columnDto
来源: https://www.cnblogs.com/Lulus/p/12765446.html