在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
XmlSerializer 使您能够控制如何将对象编码为 XML。 System.Xml.Serialization 下面举个例子说明: // This is the class that will be serialized. public class OrderedItem { public string ItemName; public string Description; public decimal UnitPrice; public int Quantity; public decimal LineTotal; // A custom method used to calculate price per item. public void Calculate() { LineTotal = UnitPrice * Quantity; } } 如何把这个类转换成一个xml文件呢,这时候就需要 XmlSerializer类来处理了。 它的Serialize(Stream, Object)这个方法,就是用来把一个user类的对象转换成xml文档的。 我们来看一个例子: using System; using System.IO; using System.Xml.Serialization;public class Test{ public static void Main(string[] args) { Test t = new Test(); // Write a purchase order. t.SerializeObject("simple.xml"); } private void SerializeObject(string filename) { Console.WriteLine("Writing With Stream"); XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem)); OrderedItem i = new OrderedItem(); i.ItemName = "Widget"; i.Description = "Regular Widget"; i.Quantity = 10; i.UnitPrice = (decimal) 2.30; i.Calculate(); // Create a FileStream to write with. Stream writer = new FileStream(filename, FileMode.Create); // Serialize the object, and close the TextWriter serializer.Serialize(writer, i); writer.Close(); } } 所生成的xml文件如下格式: <?xml version="1.0"?> <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com"> <inventory:ItemName>Widget</inventory:ItemName> <inventory:Description>Regular Widget</inventory:Description> <money:UnitPrice>2.3</money:UnitPrice> <inventory:Quantity>10</inventory:Quantity> <money:LineTotal>23</money:LineTotal> </OrderedItem>
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论