C#代码写xml文件

1.把list集合写入xml
//创建list集合
List<People> list = new List<People>();
string xmlPath = Path.GetFullPath("../../xmlFiles/ClassMember.xml");
FileInfo xmlFile = new FileInfo(xmlPath);
if (!xmlFile.Exists) {
xmlFile.Create();
}
//读取数据并写入
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
xmlDoc.AppendChild(xmlDec);
XmlElement xmlRoot = xmlDoc.CreateElement("School");
xmlDoc.AppendChild(xmlRoot);
foreach (People person in list) {
XmlElement xmlClass = xmlDoc.CreateElement("Class");
xmlRoot.AppendChild(xmlClass);
XmlAttribute xmlClassId = xmlDoc.CreateAttribute("Id");
xmlClassId.InnerText = "一年级";
xmlClass.Attributes.Append(xmlClassId);
XmlElement xmlName = xmlDoc.CreateElement("Name");
xmlName.InnerXml = person.Name;
xmlClass.AppendChild(xmlName);
XmlElement xmlAge = xmlDoc.CreateElement("Age");
xmlAge.InnerText = person.Age + "";
xmlClass.AppendChild(xmlAge);
}
xmlDoc.Save(xmlFile.FullName);
阅读更多

没有更多推荐了,返回首页