把list集合的內容寫入到Xml中,通過XmlDocument方式寫入Xml文件中


 

List<Person> list = new List<Person>
{
new Person{Name="張三",Age=20,Email="zs@zhansan.com"},
new Person{Name="李四",Age=30,Email="ls@lisi.com"},
new Person{Name="王五",Age=22,Email="ww@wangwu.com"},
new Person{Name="趙柳",Age=20,Email="xl@zhaoliou.com"},
new Person{Name="玄武",Age=20,Email="xw@xuanwu.com"},
new Person{Name="白虎",Age=20,Email="bh@baihu.com"},
};

//實例化XMLDocument對象
XmlDocument xmldoc = new XmlDocument();

//增加一個Xml文檔聲明

XmlDeclaration xmldeclaration = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);

//創建Xml文檔根節點

XmlElement xmlelement = xmldoc.CreateElement("List");

//添加到Xml文檔中
xmldoc.AppendChild(xmlelement);

//循環添加

for (int i = 0; i < list.Count; i++)
{

//創建根節點下的子節點
XmlElement xmlperson = xmldoc.CreateElement("Person");

//創建子節點的屬性ID
XmlAttribute xmlattribute = xmldoc.CreateAttribute("id");

//給屬性值賦值
xmlattribute.Value = (i + 1).ToString();

//添加到子節點中
xmlperson.Attributes.Append(xmlattribute);

//添加Name節點

XmlElement xmlName = xmldoc.CreateElement("Name");

//給Name文本賦值
xmlName.InnerText = list[i].Name;

//添加到Person節點下
xmlperson.AppendChild(xmlName);

//以下節點類似

XmlElement xmlAge = xmldoc.CreateElement("Age");
xmlAge.InnerText = list[i].Age.ToString();
xmlperson.AppendChild(xmlAge);

XmlElement xmlEmail = xmldoc.CreateElement("Email");
xmlEmail.InnerText = list[i].Email;
xmlperson.AppendChild(xmlEmail);

xmlelement.AppendChild(xmlperson);

}

//創建文件保存在Xml文件夾中

string fileName = Server.MapPath("/Xml/List.xml");

xmldoc.Save(fileName);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM