您的位置:首页 > 其它

读写XML

2015-11-23 10:22 190 查看
本文主要讲将XML数据读取到数据库中,和从读取数据库中数据写入XML,数据库使用MySql

首先脑补下XML的知识:

XML作用:存储数据
优点:每种语言都内置了XML文件分析引擎,不用单独进行文件分析引擎的编写。
XML语法规范:
1)必须区分大小写
2)文档中只能有一个根节点
3)属性值必须用双引号
4)有开始标签一定要有结束标签
5)文档声明:<?xml version="1.0" encoding="utf-8"?>

读取数据库中的数据写入到XML:
主要用到的方法时setAttributeValue和setElementValue

static void Main(string[] args)
{
DataTable table = GetDataTable();
List<Student> stuList = TableToList(table);
XDocument xdoc = new XDocument();
XElement root = new XElement("Person");
xdoc.Add(root);//添加根节点
foreach (Student stu in stuList)
{
XElement stuEle = new XElement("Student");
stuEle.SetAttributeValue("stuId",stu.Student_Id.ToString());//设置属性
stuEle.SetElementValue("name",stu.Name);//设置子节点和值
stuEle.SetElementValue("class", stu.Class);
stuEle.SetElementValue("gender", stu.Gender);
root.Add(stuEle);
}
xdoc.Save("1.xml");
Console.WriteLine("数据库写入完毕");
Console.ReadKey();
}
/// <summary>
/// 读取数据库表数据
/// </summary>
/// <returns></returns>
public static DataTable GetDataTable()
{
string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
DataSet ds= MySqlHelper.ExecuteDataset(connstr,"select * from student");
return ds.Tables[0];
}
/// <summary>
/// 将行转换为list
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static List<Student> TableToList(DataTable table)
{
List<Student> list = new List<Student>();
for (int i = 0; i < table.Rows.Count; i++)
{
Student stu = new Student();
DataRow row=table.Rows[i];
stu.Class = row["Class"].ToString();
stu.Gender = row["Gender"].ToString();
stu.Name = row["Name"].ToString();
stu.Student_Id = Convert.ToInt32(row["Student_Id"]);
list.Add(stu);
}
return list;
}


读取xml数据插入到数据库

主要用到的方法item.Attribute("Xname").value--获取属性的值 item.Element("Xname").value--获取子节点的值

string connstr = "server=localhost;database=test;user id=root;password=123";
XDocument xdoc = XDocument.Load(@"F:\tmp\1.xml");
XElement root = xdoc.Root;
foreach (XElement item in root.Elements())
{
//Console.WriteLine(item.Element("name").Value);
//Console.WriteLine(item.Element("class").Value);
//Console.WriteLine(item.Element("gender").Value);
string sql = "insert into student(Student_Id,Name,Class,Gender)values(@Student_Id,@Name,@Class,@Gender)";
MySqlParameter[] ps = {
new MySqlParameter("@Student_Id",item.Attribute("stuId").Value),//读取属性值
new MySqlParameter("@Name",item.Element("name").Value),//读取子节点值
new MySqlParameter("@Class",item.Element("class").Value),
new MySqlParameter("@Gender",item.Element("gender").Value)
};
MySqlHelper.ExecuteNonQuery(connstr, sql, ps);//插入数据库
}
Console.WriteLine("ok");
Console.ReadKey();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: