XML操作

一、写

        //创建Xdocument对象
         XDocument xDoc = new XDocument();
         //创建一个根节点,定义节点名字Student
         XElement xEle = new XElement("Student");
         //加载到XML文档
         xDoc.Add(xEle);
 
        //添加一个属性值,
         XAttribute xAttr = new XAttribute("Id","888");
         xEle.Add(xAttr);
 
         //添加节点
         XElement xEleName = new XElement("Name","lei");
         XElement xEleAge = new XElement("Age","18");
         XElement xEleGender = new XElement("Gender","");
         xEle.Add(xEleName,xEleAge,xEleGender);
         xEleAge.Value = "22";
         //保存文档
         xDoc.Save(@"d:\xmlwrite.xml");
 

   

*****************输出的XML************************* 
 <?xml version="1.0" encoding="utf-8"?>
  <Student Id="888">
  <Name>lei</Name> 
  <Age>22</Age>
  <Gender>男</Gender>
  </Student>
**************************************************

二、读

//读取XML文档
XDocument XDoc2 = XDocument.Load(@"d:\caoyi.xml");
//获取根节点
XElement Root = XDoc2.Root;
//输出根节点的Name,Value
Console.WriteLine("Root.Name:{0}",Root.Name);//输出:Student
Console.WriteLine("Root.Value:{0}",Root.Value);//输出:lei22男
Console.WriteLine("Root.ToString:{0}",Root.ToString());//输出:节点下的整个XML
//获取子元素
XElement xEle1 =Root.Element("Name");//获取子元素组
Console.WriteLine(xEle1.Value);//输出:lei
 
foreach (XElement ele in Root.Elements()) 
{
    Console.WriteLine("{0}-{1}",ele.Name,ele.Value);
}

三、序列化

       //需要写[Serializable]标签
        [Serializable]
        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }

            public char Gender { get; set; }
        }         

          List<Person> perList = new List<Person>()
            {
                new Person(){ Name="张三1",Age=19, Gender=''},
                new Person(){ Name="张三2",Age=19, Gender=''},
                new Person(){ Name="张三3",Age=19, Gender=''},
                new Person(){ Name="张三4",Age=19, Gender=''},
                new Person(){ Name="张三5",Age=19, Gender=''},
                new Person(){ Name="张三6",Age=19, Gender=''},
            };
            using (FileStream file = new FileStream("xmlserializable.xml", FileMode.Create, FileAccess.Write))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
                serializer.Serialize(file,perList);
            }    

 

posted @ 2015-10-07 23:29  Leo的日记本  阅读(169)  评论(0编辑  收藏  举报