List<Person> list=new List<Person>{ new Person(){Name="張三",Age=50,Address="重慶市沙坪壩區"}, new Person(){Name="李四",Age=20,Address="西科公寓"}, new Person(){Name ...
List<Person> list=new List<Person>{
new Person(){Name="張三",Age=50,Address="重慶市沙坪壩區"},
new Person(){Name="李四",Age=20,Address="西科公寓"},
new Person(){Name="王麻子",Age=50,Address="重慶市沙坪壩區"},
new Person(){Name="陳二狗",Age=20,Address="西科公寓"}
};
//實例化一XDocument對象
XDocument xdoc=new XDocument();
//為文檔增加一文檔聲明
XDeclaration xdecl =new XDeclaration("1.0","utf-8",null);
//創建一個根節點
XElement xelement=new XElement("List");
//把根節點添加到文檔中
xdox.Add(xelement);
for(int i=0;i<list.Count;i++){
//為根節點下添加子節點
XElement xperson=new XElement("Person");
//為節點添加屬性
xperson.SetAttributeValue("id",(i+1).ToString());
//給子節點添加文本節點
xperson.SetElementValue("Name",list[i].Name);
xperson.SetElementValue("Age",list[i].Age.ToString());
xperson.SetElementValue("Address",list[i].Address);
//添加到根節點下
xelement.Add(xperson);
}
//創建一個在Xml文件夾下的List.xml文件
string fileName=Server.MapPath("/Xml/List.xml");
//保存Xml文件
xdoc.Save(fileName);