一聚教程网:一个值得你收藏的教程网站

热门教程

LINQ生成XML格式数据与C#序列化成XML实例

时间:2022-06-25 08:16:29 编辑:袖梨 来源:一聚教程网

LINQ生成XML格式数据

 代码如下 复制代码
using System.Xml.Linq;
static void Main(string[] args)
        {
            //LINQ生成XML格式的数据,相比较把对象序列化成XML文件要灵活性好点using System.Xml.Linq;
            List list = new List
            {
                new Student{ID=1,Name="林书豪",Scores=new List{80,90,100}},
                new Student{ID=1,Name="张三丰",Scores=new List{77,88,99}}
            };
 
            var xml = new XElement("Root",
                from l in list
                let x = String.Format("{0},{1},{2}", l.Scores[0], l.Scores[1], l.Scores[2])
                select new XElement("Student",
                    new XElement("ID", l.ID),
                    new XElement("Name", l.Name),
                    new XElement("Scores", x)
                    )
                );
            Console.Write(xml);
            Console.Read();
 
            /*
           
               
                    1
                    林书豪
                    80,90,100
               

               
                    2
                    张三丰
                    877,88,99
               

           

            */
        }
 
class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List Scores;
}

 
序列化成XML文件

对象序列化成XML

 代码如下 复制代码

using System.Xml.Serialization;
public void WriteXML()
    {
        Product[] productlist = new Product[] {
            new Product(){Name="苹果",Price=5.5},
            new Product(){Name="橘子",Price=2.5},
            new Product(){Name="干柿子",Price=16.00}
        };
        XmlSerializer writer = new XmlSerializer(typeof(Product[]));
 

        StreamWriter file = new StreamWriter(Server.MapPath("product.xml"));
        writer.Serialize(file, productlist);
        file.Close();
    }
 

    public class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }
生成一个XML文件:

 

    苹果

    5.5

 

 

    橘子

    2.5

 

 

    干柿子

    16

 

热门栏目