Using Xml Linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c: emp est.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Make", typeof(string));
dt.Columns.Add("Make Attribute", typeof(string));
dt.Columns.Add("Model", typeof(string));
dt.Columns.Add("Model Attribute", typeof(string));
dt.Columns.Add("Year", typeof(string));
dt.Columns.Add("Year Attribute", typeof(string));
dt.Rows.Add(new object[] { "Honda", "Common", "H1245", "Cfpd", "1975", "Markel" });
dt.Rows.Add(new object[] { "Honda", "Common", "H1245", "Cfpd", "1975", "Markel" });
dt.Rows.Add(new object[] { "Honda", "Common", "H1245", "Cfpd", "1975", "Markel" });
Vehicle.Serialize(dt, FILENAME);
}
}
public class Vehicle
{
public static void Serialize(DataTable dt, string fileName)
{
string ident =
"<?xml version="1.0" encoding="utf-8"?>" +
"<Vehicles xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">" +
"</Vehicles>";
XDocument doc = XDocument.Parse(ident);
XElement xVehicles = doc.Root;
foreach (DataRow row in dt.AsEnumerable())
{
XElement xVehicle = new XElement("Vehicle", new object[] {
new XElement("Make", new object[] {new XAttribute("applicableTo", row.Field<string>("Make Attribute")), row.Field<string>("Make")}),
new XElement("Make", new object[] {new XAttribute("applicableTo", row.Field<string>("Model Attribute")), row.Field<string>("Model")}),
new XElement("Make", new object[] {new XAttribute("applicableTo", row.Field<string>("Year Attribute")), row.Field<string>("Year")})
});
xVehicles.Add(xVehicle);
}
doc.Save(fileName);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…