LINQ generates XML Format data
The code is as follows |
Copy Code |
Using System.Xml.Linq; static void Main (string[] args) { LINQ generates XML-formatted data, which is more flexible than using System.Xml.Linq, compared to serializing an object into an XML file. list<student> list = new list<student> { New Student{id=1,name= "Jeremy Lin", Scores=new list<int>{80,90,100}}, New Student{id=1,name= "Zhang San Feng", 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> Lin </Name> <Scores>80,90,100</Scores> </Student> <Student> <ID>2</ID> <Name> Zhang </Name> <Scores>877,88,99</Scores> </Student> </Root> */ }
Class Student { public int ID {get; set;} public string Name {get; set;} Public list<int> Scores; } |
serializing to an XML file
Object serialized into XML
The code is as follows |
Copy Code |
Using System.Xml.Serialization; public void WriteXml () { product[] ProductList = new product[] { New Product () {name= "Apple", price=5.5}, New Product () {name= "orange", price=2.5}, New Product () {name= "dry persimmon", 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;} } To generate an XML file: <?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> Apple </Name> <Price>5.5</Price> </Product> <Product> <Name> Orange </Name> <Price>2.5</Price> </Product> <Product> <Name> dried Persimmon </Name> <Price>16</Price> </Product> </ArrayOfProduct> |