I have a problem, and i cant figure out what is the matter. I want to insert elements to my XML file from a listbox. In the listbox there are Menuelem elements, which has a string and an int variable.
dt = DateTime.Now;
XDocument doc = XDocument.Load(path);
XElement user = new XElement("user", new XAttribute("id", id),
new XElement("order", new XAttribute("id", key),
new XElement("date", dt.ToString()))
);
doc.Element("orders").Add(user);
doc.Save(path);
foreach (Menuelem item in listBox6.Items)
{
int j=0;
var menuelem = new XElement("menuelem", new XAttribute("db", j),
new XElement("name", item.Nev),
new XElement("price", item.Ar));
doc.Element("order").Add(menuelem); //throws nullreferenceexception
doc.Save(path);
j++;
}
listBox6.Items.Clear();
label3.Text = "";
key++;
}
What I want to look my XML is like this:
<?xml version="1.0" encoding="utf-8" ?>
<orders>
<user id="0">
<order id="0">
<date>2012.11.19. 2:16:12</date>
<menuelem db = "0">
<name>asdasdas</name>
<price>1000</price>
<menuelem db = "1">
<name>asds</name>
<price>2000</price>
</order>
<user id="0">
<order id="1">
<date>2012.11.19. 2:16:15</date>
<menuelem db = "0">
<name>asdasdas</name>
<price>1000</price>
<menuelem db = "1">
<name>asds</name>
<price>2000</price>
</order>
</user>
</orders>
Can anyone solve this using linq?
You code tries to find “order” element as immediate child of the document which contains only root element (“orders”) and as result getting
null. SeeElementfor details on what it searches for elements and when returnsnull.You need to correctly select your newly inserted element. Simple option is to use
Descendantsby name and select last one (which is the user just added by Add)Easier option is to build “user” element completely and than add it to the tree. Than you don’t need to search document for nodes just added to it.