Olaru Mircea
Olaru Mircea

Reputation: 2620

xml c# add element with Linq to Xml

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!

Upvotes: 1

Views: 408

Answers (2)

Jens Kloster
Jens Kloster

Reputation: 11277

try this:

 xDoc.Descendants("SQUIBLIST")
      .FirstOrDefault()
      .Add(
             new XElement("Sensor", 
             new XAttribute("ID", id + 1), 
             new XAttribute("Name", "Squib" + (id + 1).ToString()), 
             new XAttribute("Used", "True")
             ,"" //<-- this will represent the value of <Sensor>
));

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500525

You can include an empty string to force it to add an empty text node:

new XElement("Sensor", 
    new XAttribute("ID", id + 1), 
    new XAttribute("Name", "Squib" + (id + 1).ToString()),
    new XAttribute("Used", "True"),
    "")

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 a NullReferenceException if there aren't any SQUIBLIST elements. It would at least be clearer to use First() so that that can fail if there are no such elements, rather than returning null.

Upvotes: 4

Related Questions