我遇到了一个问题:我正在从目录中读取多个xml文件,并从中提取数据。但是如果一个或多个xml文件有错误或形成错误,则异常会中断该过程。
我知道"接下来的错误恢复"这不是一个好习惯,但是 如何才能恢复错误?不要打断......
try
{
foreach (string file in Directory.EnumerateFiles(path, "*.xml"))
{
xDoc.Load(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), file));
string strpath = xDoc.BaseURI;
XmlNodeList nodeList = xDoc.SelectNodes("/Employees/Employee[*]"); //para que elija TODOS
//Loop through the selected Nodes.
foreach (XmlNode node in nodeList)
{
dr = CartDT.NewRow();
dr["Employee_Id"] = node.Attributes["Id"].Value.ToString();
dr["EmployeeName"] = node["EmployeeName"].InnerText;
dr["City"] = node.Attributes["City"].Value.ToString();
dr["Country"] = node["Country"].InnerText;
dr["Comisiones"] = node["Comisiones"].InnerText;
CartDT.Rows.Add(dr);
}
}
}
catch (System.Xml.XmlException)
{
drError = dtError.NewRow();
//Here==> how can I continue the process?
}
gvXML.DataSource = CartDT;
gvXML.DataBind();
CartDT.Rows.Clear();
}
拜托,我希望有人可以帮助我。 谢谢 最诚挚的问候......
谢谢Sami Kuhmonen 你是对的......这是最简单的方法。我可以得到错误报告:
//Crear las columnas del DataTable de Datos
CartDT.Columns.Add("Employee_Id", typeof(string));
CartDT.Columns.Add("EmployeeName", typeof(string));
CartDT.Columns.Add("City", typeof(string));
CartDT.Columns.Add("Country", typeof(string));
CartDT.Columns.Add("Comisiones", typeof(string));
//Crear las columnas del DataTable de Errores
dtError.Columns.Add("Archivo", typeof(string));
dtError.Columns.Add("Observaciones", typeof(string));
foreach (string file in Directory.EnumerateFiles(path, "*.xml"))
{
try
{
xDoc.Load(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), file));
string strpath = xDoc.BaseURI;
XmlNodeList nodeList = xDoc.SelectNodes("/Employees/Employee[*]"); //para que elija TODOS
//Loop through the selected Nodes.
foreach (XmlNode node in nodeList)
{
dr = CartDT.NewRow();
dr["Employee_Id"] = node.Attributes["Id"].Value.ToString();
dr["EmployeeName"] = node["EmployeeName"].InnerText;
dr["City"] = node.Attributes["City"].Value.ToString();
dr["Country"] = node["Country"].InnerText;
dr["Comisiones"] = node["Comisiones"].InnerText;
CartDT.Rows.Add(dr);
}
}
catch (System.Xml.XmlException)
{
drError = dtError.NewRow(); //Preparamos fila para error
drError["Archivo"] = Path.GetFileName(file); //Nombre del Archivo
drError["Observaciones"] = "Error de Contenido XML";
dtError.Rows.Add(drError);
//mandar la informacion de error a la grilla
gvError.DataSource = dtError;
gvError.DataBind();
}
}
//mandar la informacion a la grilla
gvXML.DataSource = CartDT;
gvXML.DataBind();
CartDT.Rows.Clear(); //Limpiar el DataTable
dtError.Rows.Clear();//Limpiar el DataTable de errores
}
非常感谢...
答案 0 :(得分:5)
如果在foreach
循环内移动try ... catch块。然后,如果一个失败,其他人仍然被处理。