XML到DataTable

时间:2014-06-03 07:11:52

标签: linq-to-xml

我想读取XML文件,为Data Table&分配值。将其存储到SQL表中。我将使用SqlBulkCopy类将记录插入到数据库中。

以下是示例XML文件

<?xml version="1.0" encoding="utf-8" ?>
<Customers>
  <Customer Pan= 'AKGPA4617H' CustName='XYZ'>
     <Accounts>
        <Bank>AXIS BANK</Bank>
        <Branch>Ville Parle</Branch>
        <Type>Saving</Type>
        <Balance> 5000</Balance>
     </Accounts>
    <Accounts>
        <Bank>AXIS BANK</Bank>
        <Branch>Dadar</Branch>
        <Type>Saving</Type>
        <Balance>7000</Balance>
     </Accounts>
  </Customer>
<Customer Pan='AKGPS1234H' CustName='ABC'>
      <Accounts>
        <Bank>AXIS BANK</Bank>
        <Branch>Ville Parle</Branch>
        <Type>Saving</Type>
        <Balance>6000</Balance>
     </Accounts>
 </Customer>
</Customers>

先谢谢..

1 个答案:

答案 0 :(得分:0)

它有效......

        var Sample = from a in xd.Descendants("Customers").Elements("Customer")
                     from b in a.Elements("Accounts")
                     select new
        {
            CustPAN = a.Attributes("Pan").FirstOrDefault().Value,
            CustName = a.Attributes("CustName").FirstOrDefault().Value,
            Bank = b.Element("Bank").Value,
            Branch = b.Element("Branch").Value,
            Type = b.Element("Type").Value,
            Balance = b.Element("Balance").Value

        };

        DataTable dtSample = new DataTable();
        dtSample.Columns.Add("CustPAN");
        dtSample.Columns.Add("CustName");
        dtSample.Columns.Add("Bank");
        dtSample.Columns.Add("Branch");
        dtSample.Columns.Add("Type");
        dtSample.Columns.Add("Balance");

        foreach (var value in Sample)
        {
            DataRow dr = dtSample.NewRow();
            dr["CustPAN"] = value.CustPAN;
            dr["CustName"] = value.CustName;
            dr["Bank"] = value.Bank;
            dr["Branch"] = value.Branch;
            dr["Type"] = value.Type;
            dr["Balance"] = value.Balance;

            dtSample.Rows.Add(dr);

        }