在我当前的项目中,我使用System.IO.Stream将xml文件读入DataSet。
父节点NewDataSet
内有超过100个子节点记录。我在下面附加了XML模式:
但是,当我对DataSet Tables进行计数时,它只返回1个表。
FileStream fileStream = new FileStream(sourceFilePath, FileMode.Open);
try
{
dataSet.ReadXml(fileStream);
if (dataSet.Tables.Count> 0)
{
//dt = dataSet.Tables[0];
for (int i = 0; i < dataSet.Tables.Count; i++)
{
dataTable = dataSet.Tables[i];
if (dataTable != null)
{
SalesHeader salesHeader = new SalesHeader();
salesHeader.OutletCode = dataTable.Rows[i]["OutletCode"].ToString();
salesHeader.TransactionNo = dataTable.Rows[i]["TransactionNo"].ToString();
salesHeader.TransactionDate = Convert.ToDateTime(dataTable.Rows[i]["TransactionDate"]);
salesHeader.ShiftNo = Convert.ToInt16(dataTable.Rows[i]["ShiftNo"]);
salesHeader.TotalAmount = Convert.ToDecimal(dataTable.Rows[i]["TotalAmount"]);
salesHeader.TenderAmount = Convert.ToDecimal(dataTable.Rows[i]["TenderAmount"]);
salesHeader.ChangeAmount = Convert.ToDecimal(dataTable.Rows[i]["ChangeAmount"]);
salesHeader.TransactionStatus = Convert.ToInt16(dataTable.Rows[i]["TransactionStatus"]);
salesHeader.BusinessDate = Convert.ToDateTime(dataTable.Rows[i]["BusinessDate"]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
fileStream.Close();
}
我认为它只是读取父节点而无法到达子节点。谁能告诉我如何解决这个问题?任何帮助将非常感谢!
答案 0 :(得分:2)
我完全同意哈姆雷特,你的代码是有效的!您不应该遍历表,您应该迭代表中的行:
FileStream fileStream = new FileStream(sourceFilePath, FileMode.Open);
try
{
List<SalesHeader> result = new List<SalesHeader>();
dataSet.ReadXml(fileStream);
if (dataSet.Tables.Count> 0)
{
dataTable = dataSet.Tables[0];
if (dataTable != null)
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
SalesHeader salesHeader = new SalesHeader();
salesHeader.OutletCode = dataTable.Rows[i]["OutletCode"].ToString();
salesHeader.TransactionNo = dataTable.Rows[i]["TransactionNo"].ToString();
salesHeader.TransactionDate = Convert.ToDateTime(dataTable.Rows[i]["TransactionDate"]);
salesHeader.ShiftNo = Convert.ToInt16(dataTable.Rows[i]["ShiftNo"]);
salesHeader.TotalAmount = Convert.ToDecimal(dataTable.Rows[i]["TotalAmount"]);
salesHeader.TenderAmount = Convert.ToDecimal(dataTable.Rows[i]["TenderAmount"]);
salesHeader.ChangeAmount = Convert.ToDecimal(dataTable.Rows[i]["ChangeAmount"]);
salesHeader.TransactionStatus = Convert.ToInt16(dataTable.Rows[i]["TransactionStatus"]);
salesHeader.BusinessDate = Convert.ToDateTime(dataTable.Rows[i]["BusinessDate"]);
result.Add(saleshaeder);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
fileStream.Close();
}