笔记18
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;
namespace SerlizeXml
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Serialize(AppDomain.CurrentDomain.BaseDirectory + "litao.xml");
}
public void Serialize(string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(Region));
StreamWriter writer = new StreamWriter(fileName);
SalesProduct product1 = new SalesProduct();
product1.Name = "Sofa";
product1.IsTaxable = true;
Product productDisplay = new Product();
productDisplay.Name = "Television";
Region region = new Region();
region.Name = "East";
region.Products = new Product[] { product1,productDisplay};
serializer.Serialize(writer, region);
writer.Close();
}
}
public class Product
{
private int ID;
public string Name;
}
public class SalesProduct : Product
{
[XmlAttribute("Taxable")]
public bool IsTaxable;
}
public class Region
{
[XmlAttribute("Area")]
public string Name;
[XmlArrayItem(typeof(Product), ElementName = "Product")]
[XmlArrayItem(typeof(SalesProduct), ElementName = "SalesProduct")]
public Product[] Products;
}
}
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;
namespace SerlizeXml
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Serialize(AppDomain.CurrentDomain.BaseDirectory + "litao.xml");
}
public void Serialize(string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(Region));
StreamWriter writer = new StreamWriter(fileName);
SalesProduct product1 = new SalesProduct();
product1.Name = "Sofa";
product1.IsTaxable = true;
Product productDisplay = new Product();
productDisplay.Name = "Television";
Region region = new Region();
region.Name = "East";
region.Products = new Product[] { product1,productDisplay};
serializer.Serialize(writer, region);
writer.Close();
}
}
public class Product
{
private int ID;
public string Name;
}
public class SalesProduct : Product
{
[XmlAttribute("Taxable")]
public bool IsTaxable;
}
public class Region
{
[XmlAttribute("Area")]
public string Name;
[XmlArrayItem(typeof(Product), ElementName = "Product")]
[XmlArrayItem(typeof(SalesProduct), ElementName = "SalesProduct")]
public Product[] Products;
}
}
串行化后生成的litao.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<Region xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Area="East">
<Products>
<SalesProduct Taxable="true">
<Name>Sofa</Name>
</SalesProduct>
<Product>
<Name>Television</Name>
</Product>
</Products>
</Region>
<Region xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Area="East">
<Products>
<SalesProduct Taxable="true">
<Name>Sofa</Name>
</SalesProduct>
<Product>
<Name>Television</Name>
</Product>
</Products>
</Region>