Reputation: 11
my XML file structure is
<Invoices>
<Invoice>
<Date>1-1-1</Date>
<ID>1</ID>
<Items></Items>
<Total>1</Total>
</Invoice>
</Invoices>
i want to add child node to new node is
<Item>
<Model>1</Model>
<Quantity>1</Quantity>
<ItemPrice>1</ItemPrice>
</Item>
i want to add this node several times (items may contain several item nodes) i put it in loop code here :
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);
}
consider i = 3 the output is a single node not a three child nodes can u help please .....
Upvotes: 1
Views: 1553
Reputation: 236228
You can easily do that with 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);
Or even without loop:
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);
If you want to add items to last invoice:
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
Upvotes: 2