在对象和 xml 文档之间进行序列化和反序列化操作。"> xmlserializer 使您能够控制如何将对象编码为 xml。
">命名空间: system.xml.serialization
程序集: system.xml(位于 system.xml.dll)
下面举个例子说明:
// 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"); } privatevoid 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>
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!