日期:2014-05-17 浏览次数:20974 次
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
namespace 生成XML文档
{
class Program
{
static void Main(string[] args)
{
List<Customers> list = new List<Customers>();
Customers c1 = new Customers("张三", "1001", 534.78, 2);
Customers c2 = new Customers("李四", "1002", 345.34, 1);
list.Add(c1);
list.Add(c2);
//list = GetXmlToCustomer(@"C:\Customer.xml");
XDocument xdoc = GetCustomersToXML(list.ToArray());
//把获得的XML文档保存到C:\Customer.xml
File.WriteAllText(@"C:\Customer.xml", xdoc.ToString(), Encoding.UTF8);
Console.ReadKey();
}
/// <summary>
/// 把Customers[]转换为XDocument
/// </summary>
/// <param name="customers">Customers[]数组</param>
/// <returns>Customers[]数组的XDocument</returns>
static XDocument GetCustomersToXML(Customers[] customers)
{
XDocument xdoc = new XDocument();
XElement root = new XElement("data");
foreach (Customers ct in customers)
{
XElement xct = new XElement("Customer");
//姓名节点
XElement xName = new XElement("姓名");
xName.Value = ct.Name;
xct.Add(xName);
//编号节点
XElement xNum = new XElement("编号");
xNum.Value = ct.CustomerNum.ToString();
xct.Add(xNum);
//金额节点
XElement xMoney = new XElement("金额");
xMoney.Value = ct.Money.ToString();
xct.Add(xMoney);
//类型节点
XElement xType = new XElement("类型");
xType.Value = ct.CustomerType.ToString();
xct.Add(xType);
root.Add(xct);
}
xdoc.Add(root);
return xdoc;
}
static List<Customers> GetXmlToCustomer(string customerXmlPath)
{
List<Customers> list = new List<Customers>();
using (Stream st = File.OpenRead(customerXmlPath))
{
using (StreamReader sr = new StreamReader(st, Encoding.UTF8))
{
XDocument xdoc = XDocument.Load(sr);
XElement root = xdoc.Root;
foreach (XElement xe in root.Elements())
{
Customers ct = new Customers();
XElement[] customer = xe.Elements().ToArray();
ct.Name = customer[0].Value;
ct.CustomerNum = customer[1].Value;
ct.Money = Convert.ToDouble(customer[2].Value);
ct.CustomerType = Convert.ToInt32(customer[3].Value);
list.Add(ct);
}
}
}
return list;