数组格式如下
{[张三]|[1001]|[10.2]|[2]|}|{[李四]|[1002]|[11.2]|[2]|}..
XML格式如下:
<data>
<姓名>张三</姓名>
<编码>1001</编码>
<金额>10.2</金额>
<类型>2</类型>
</data>
<data>
<姓名>李四</姓名>
<编码>1002</编码>
<金额>11.2</金额>
<类型>2</类型>
</data>
..
如何进行互转呢?万分感谢
{[张三]|[1001]|[10.2]|[2]|}|{[李四]|[1002]|[11.2]|[2]|}..
XML格式如下:
<data>
<姓名>张三</姓名>
<编码>1001</编码>
<金额>10.2</金额>
<类型>2</类型>
</data>
<data>
<姓名>李四</姓名>
<编码>1002</编码>
<金额>11.2</金额>
<类型>2</类型>
</data>
..
如何进行互转呢?万分感谢
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;
}
}
class Customers
{
//Fields
public string Name { get; set; }
public string CustomerNum { get; set; }
public double Money { get; set; }
public int CustomerType { get; set; } //method
public Customers()
{
}
public Customers(string name, string num, double money, int customerType)
{
this.Name = name;
this.CustomerNum = num;
this.Money = money;
this.CustomerType = customerType;
}
}
}