如何从一个表中获取数据并添加到C#DataSet中的另一个表中?

时间:2017-05-25 17:38:05

标签: c# sql-server xml

我有一个复杂的xml文件,我读取了xml并将数据存储到DataSet对象中。 DataSet包含以下DataTable

1.Customer
2.Operation 
3.Account 
4.Card

客户 DataTable有许多列,包含CustomerId和SerialNo。其他DataTable有Seri​​alNo列常见。我需要根据SerialNo将CustomerId Column值添加到其他(Operation,Account和card)DataTable中,并且需要将所有表数据存储到数据库中。我怎么能这样做,请举个例子告诉我。

1 个答案:

答案 0 :(得分:0)

C#代码:

 DataSet ds = new DataSet();
        try
        {
            ds.ReadXml(@"D:\Test.xml");               

            DataTable dtstatement = ds.Tables["Statement"];

            foreach (DataRow dr in dtstatement.Rows)
            {
                Statement statement = new Statement();
                statement.IdClient = Convert.ToInt32(dr["IdClient"].ToString());
                statement.StatementNo = Convert.ToInt32(dr["StatementNo"].ToString());

                DataRow[] selectedCards = ds.Tables["card"].Select(string.Format("StatementNo = {0}", statement.StatementNo));
                if (selectedCards.Length > 0)
                {
                    foreach (var item in selectedCards)
                    {
                        Card card = new Card();
                        card.IdClient = statement.IdClient;
                        card.CardNo = item["cardNo"].ToString();
                    }
                }
                DataRow[] selectedAccounts = ds.Tables["Account"].Select("StatementNo = " + statement.StatementNo);
                if (selectedAccounts.Length > 0)
                {
                    foreach (var item in selectedAccounts)
                    {
                        Account account = new Account();
                        account.IdClient = statement.IdClient;
                        account.AccountNo = item["AccountNo"].ToString();
                    }
                }
            }
        }
        catch (Exception ex)
        {

        }

<强> XML:

<?xml version="1.0" encoding="utf-8"?>
<Statements>
 <Statement>
    <StatementNo>1</StatementNo>
    <IdClient>101</IdClient>
    <Cards>
        <card>
            <StatementNo>1</StatementNo>
            <cardNo>123456</cardNo>
        </card>
        <card>
            <StatementNo>1</StatementNo>
            <cardNo>1234567</cardNo>
        </card>
    </Cards>
    <Accounts>
        <Account>
            <StatementNo>1</StatementNo>
            <AccountNo>123456</AccountNo>
        </Account>
        <Account>
            <StatementNo>1</StatementNo>
            <AccountNo>1234567</AccountNo>
        </Account>
    </Accounts>
</Statement>
 <Statement>
    <StatementNo>2</StatementNo>
    <IdClient>102</IdClient>
    <Cards>
        <card>
            <StatementNo>2</StatementNo>
            <cardNo>12345678</cardNo>
        </card>         
    </Cards>
  </Statement>
</Statements>