i need some help in adding an element, right now i am doing this :
XDocument xDoc = XDocument.Load(testFile);
xDoc.Descendants("SQUIBLIST")
.FirstOrDefault()
.Add(new XElement("Sensor",
new XAttribute("ID", id + 1),
new XAttribute("Name", "Squib" + (id + 1).ToString()),
new XAttribute("Used", "True")));
xDoc.Save(testFile);
and i am getting ( for example ):
<Sensor ID="26" Name="Squib26" Used="True" />
what i want is this :
<Sensor ID="26" Name="Squib26" Used="True"></Sensor>
and i can’t find the way to do it.
Pease give me a clue . Thanks!
You can include an empty string to force it to add an empty text node:
However, you should consider why you really need this. Typically applications reading the XML simply shouldn’t care about the difference.
Also note that by calling
FirstOrDefault().Add(...)you’ll fail with aNullReferenceExceptionif there aren’t anySQUIBLISTelements. It would at least be clearer to useFirst()so that that can fail if there are no such elements, rather than returningnull.