从DataSet中写入读取XML

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"]);
            }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值