我有以下代码应该执行以下操作:
如果有来自Web服务的xml格式的记录,则遍历每条记录,获取ErrorCode,ErrorMessage和ID。电邮该信息。然后解析出每条记录并将子元素写入表中。问题是它写的记录数和记录数一样多。我似乎无法弄清楚为什么。电子邮件部分按预期工作。
以下是代码:
#region If There Are RecordsInError From Broker Acknowledgement
if (srca.NumberOfResponseRecordsInError != "0")
{
int TotalCount ;
int.TryParse(srca.NumberOfResponseRecordsInError,out TotalCount);
string[] ErrorCode = new string[TotalCount];
string[] ErrorMessage = new string[TotalCount];
string EmailBody = null;
string StateRequestRecordGUID = null;
for (int i = 0; i < TotalCount; i++)
{
//ZJR: Populate the string arrays with Error
ErrorCode[i] = srca.FailedSeparationResponse[i].ErrorOccurrence[0].ErrorCode;
ErrorMessage[i] = srca.FailedSeparationResponse[i].ErrorOccurrence[0].ErrorMessage;
StateRequestRecordGUID = srca.FailedSeparationResponse[i].StateRequestRecordGUID;
//ZJR: Database connection to insert Error Records
SqlConnection conn4 = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=test_BdbCSSQL01;Persist Security Info=False;Integrated Security=SSPI;");
conn4.Open();
string sql = "SELECT * FROM ERROROfSIDESStagingOUT";
SqlDataAdapter da = new SqlDataAdapter(sql, conn4);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
XDocument doc = XDocument.Load("XmlString.xml");
XNamespace ns = "https://uidataexchange.org/schemas";
var node = doc.Descendants(ns + "EmployerTPASeparationResponse");
using (da)
{
foreach (var param in node.Elements())
{
try
{
if (dr.Table.Columns.Contains(param.Name.LocalName))
{
dr[param.Name.LocalName] = param.Value;
}
//param.NextNode;
}
catch (Exception ee)
{
string asdf = ee.ToString();
}
}
SqlCommandBuilder sb = new SqlCommandBuilder(da);
da.Update(dt);
}
if (conn4 != null)
{
conn4.Close();
}
//ZJR: Build the Email Body
EmailBody = EmailBody + "StateRequestRecordGUID: " + StateRequestRecordGUID + Environment.NewLine + "ErrorCode: " + ErrorCode[i] + " : " + ErrorMessage[i] + Environment.NewLine + Environment.NewLine;
SendEmail mail = new SendEmail();
mail.Send(EmailBody, "Sides Error Event");
}
}
#endregion
答案 0 :(得分:0)
我发现了问题。这是使用(da)线。我摆脱了这个,代码很好用。