LINQ生成XML格式数据
代码如下 | 复制代码 |
using System.Xml.Linq; static void Main(string[] args) { //LINQ生成XML格式的数据,相比较把对象序列化成XML文件要灵活性好点using System.Xml.Linq; List<Student> list = new List<Student> { new Student{ID=1,Name="林书豪",Scores=new List<int>{80,90,100}}, new Student{ID=1,Name="张三丰",Scores=new List<int>{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(); /* <Root> <Student> <ID>1</ID> <Name>林书豪</Name> <Scores>80,90,100</Scores> </Student> <Student> <ID>2</ID> <Name>张三丰</Name> <Scores>877,88,99</Scores> </Student> </Root> */ } class Student { public int ID { get; set; } public string Name { get; set; } public List<int> 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")); public class Product <?xml version="1.0" encoding="utf-8"?> <ArrayOfProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Product> <Name>苹果</Name> <Price>5.5</Price> </Product> <Product> <Name>橘子</Name> <Price>2.5</Price> </Product> <Product> <Name>干柿子</Name> <Price>16</Price> </Product> </ArrayOfProduct> |
时间: 2024-10-26 22:12:11