从DataSet中写入读取XML

来源:互联网 发布:怎么在淘宝上卖二手书 编辑:程序博客网 时间:2024/04/29 16:52

1、写入XML

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace UpdatingData
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection thisConnection = new SqlConnection(@"Server = .sqlexpress;Integrated Security = true;" + "Database = northwind");
            SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT CustomerID,CompanyName FROM Customers", thisConnection);
            SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
            DataSet thisDataSet = new DataSet();
            SqlDataAdapter CustAdapter = new SqlDataAdapter("SELECT * FROM Customers", thisConnection);
            SqlDataAdapter OrderAdapter = new SqlDataAdapter("SELECT * FROM Orders", thisConnection);
           CustAdapter.Fill(thisDataSet,"Customers");
            OrderAdapter.Fill(thisDataSet,"Orders");
            DataRelation thisRelation = thisDataSet.Relations.Add("CustOrder",
                thisDataSet.Tables["Customers"].Columns["CustomerID"],
                thisDataSet.Tables["Orders"].Columns["CustomerID"]);

            thisRelation.Nested = true;//relation对象的nested属性通知WriteXML()方法 将订单细节和订单嵌套在XML每个父客户之下 易于分析XML文件

            thisDataSet.WriteXml(@"C: /tmp/winddata.xml");
            Console.WriteLine(@"Successfully wrote xml output to file C:/tmp/winddata.xml");

            //foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows)
            //{
            //    Console.WriteLine(custRow["CustomerID"] +" "+ custRow["CompanyName"]);
            //    foreach (DataRow orderRow in custRow.GetChildRows(thisRelation))
            //    {
            //        Console.WriteLine(orderRow["OrderID"]);
            //    }
            //}

            //thisAdapter.Update(thisDataSet, "Customers");

            thisConnection.Close();
        }
    }
}

红字是从DataSet中写入XML 兰字从DataSet中写入数据库

 

 

2、读取XML

            DataSet thisDataSet = new DataSet();
            thisDataSet.ReadXml(@"C:/tmp/nwinddata.xml");
            foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows)
            {
                Console.WriteLine("CustomerID:" + custRow["CustomerID"] + "Name:" + custRow["CompanyName"]);
            }

原创粉丝点击