我的XML文件结构是
<Invoices>
<Invoice>
<Date>1-1-1</Date>
<ID>1</ID>
<Items></Items>
<Total>1</Total>
</Invoice>
</Invoices>
我想添加子节点
新节点<Item>
<Model>1</Model>
<Quantity>1</Quantity>
<ItemPrice>1</ItemPrice>
</Item>
我想多次添加此节点(项目可能包含多个项目节点) 我把它放在循环代码中:
for (int i = 0; i < (dataGridView2.Rows.Count - 1); i++)
{
Model.InnerText = n[i, 0].ToString() ;
Quantity.InnerText = n[i, 1].ToString();
ItemPrice.InnerText = n[i, 2].ToString();
Item.AppendChild(Model);
Item.AppendChild(Quantity);
Item.AppendChild(ItemPrice);
Items.AppendChild(Item);
}
考虑i = 3,输出是单个节点而不是三个子节点 你可以帮忙吗.....
答案 0 :(得分:2)
您可以使用LINQ to XML轻松完成此操作:
XDocument xdoc = XDocument.Load(path_to_xml);
// or with XPath: xdoc.XPathSelectElement("Invoices/Invoice/Items");
XElement items = xdoc.Root.Element("Invoice").Element("Items");
for(int i = 0; i < (dataGridView2.Rows.Count - 1); i++)
{
var item = new XElement("Item",
new XElement("Model", n[i, 0]),
new XElement("Quantity", n[i, 1]),
new XElement("ItemPrice", n[i, 2]));
items.Add(item);
}
xdoc.Save(path_to_xml);
甚至没有循环:
var xdoc = XDocument.Load(path_to_xml);
xdoc.Root.Element("Invoice").Element("Items")
.Add(Enumerable.Range(0, dataGridView2.Rows.Count - 1)
.Select(i => new XElement("Item",
new XElement("Model", n[i, 0]),
new XElement("Quantity", n[i, 1]),
new XElement("ItemPrice", n[i, 2]))));
xdoc.Save(path_to_xml);
如果要将项目添加到上次发票:
XElement invoice = xdoc.Root.Elements("Invoice").LastOrDefault();
if (invoice == null)
{
// throw exception or create and add new Invoice element
}
XElement items = invoice.Element("Items");
if (items == null)
{
// throw exception or create and add new Items element
}
// create and add Item elements to items, as described above