【发布时间】:2015-11-05 13:36:40
【问题描述】:
我有以下代码可以正确创建带有第一条记录的 xml 文档。但这只是因为我在添加第一条记录(行)后包含了一个中断
xdoc.Add(line);
break;
如果我让循环运行(为了添加所有记录)我会得到异常
错误:{“此操作将创建结构不正确的文档。”}
在这里进行了搜索,发现了很多示例,但我无法完全理解它们以及它们与我正在尝试做的事情之间的关系。
XDocument xdoc = new XDocument();
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
XElement line = new XElement("line");
XElement itemid = new XElement("field", dr.Cells["Item ID"].Value.ToString());
itemid.Add(new XAttribute("name", "item_id"));
line.Add(itemid);
XElement itemname = new XElement("field", dr.Cells["Item Name"].Value.ToString());
itemname.Add(new XAttribute("name", "item_name"));
line.Add(itemname);
XElement cost = new XElement("field", dr.Cells["Cost"].Value.ToString());
cost.Add(new XAttribute("name", "cost"));
line.Add(cost);
xdoc.Add(line);
break;
}
xdoc.Save(@"C:\xmltest\test3.xml");
当我中断时它会添加第一行,为什么当我删除中断时不添加其余行?
【问题讨论】:
标签: c# linq datagridview linq-to-xml