user1548103
user1548103

Reputation: 869

Difficulty appending to XML file using Linq

I have an XML Document that looks like

<Settings>
    <Config>
       <type>stuff</type>
       <length>stuff</length>
        <ID>1</ID>
     </Config>
</Settings>

I am attempting to append to it using

Document loadedDoc = XDocument.Load (file);
loadedDoc.Element("Settings").Add(new XElement("Config"),
                                  new XElement("type", "stuff"),
                                  new XElement("length", "stuff"),
                                  new XElement("ID", "2"));
loadedDoc.Save(file);

What I am getting when I do this is

<Settings>
    //the other configs hidden for readability
     <Config />  <--- WHAT DO?! 0_o
     <type>stuff</type>
     <length>stuff</length>
     <ID>2</ID>
</Settings>

Could someone better versed in linq tell me what it is I'm doing wrong to make it create an empty config element like that? Thanks!

Upvotes: 0

Views: 86

Answers (3)

nercan
nercan

Reputation: 207

try this

XDocument loadedDoc = XDocument.Load(file);

        loadedDoc.Element("Settings").Add(new XElement("Config"));
        loadedDoc.Element("Settings").Element("Config").Add(            
                                     new XElement("type", "stuff"),
                                     new XElement("length", "stuff"),
                                     new XElement("ID", "2"));

        loadedDoc.Save(file);

Upvotes: 1

alex
alex

Reputation: 12654

That's because you are appending to Settings, and not to Config

Try:

  loadedDoc.Element("Settings").Add(
        new XElement("Config",
                     new XElement("type", "stuff"),
                     new XElement("length", "stuff"),
                     new XElement("ID", "2")));

Upvotes: 3

Servy
Servy

Reputation: 203847

You need to add the sub elements through the "Config" element's constructor, rather than through the "Settings" constructor:

loadedDoc.Element("Settings").Add(new XElement("Config",
                             new XElement("type", "stuff"),
                             new XElement("length", "stuff"),
                             new XElement("ID", "2")));

Upvotes: 4

Related Questions