JohnP
JohnP

Reputation: 402

Adding new elements to multiple nodes in existing XML file

I have the following XML file, that currently has 100+ client nodes, and I want to add elements to each of them using C#.

My XML file structure is as follows:

    <file_specs>
  <client>
    <account_number></account_number>
    <client_name></client_name>
    <file_type></file_type>
    <file_extension></file_extension>
    <file_hasdelimiter></file_hasdelimiter>
    <file_delimiter></file_delimiter>
    <central_one>false</central_one>
    <central_code>none</central_code>
    <central_two>false</central_two>
    <c_two_code>none</c_two_code>
    <header_line>true</header_line>
    <has_quotes>true</has_quotes>
    <start_line>1</start_line>
    <has_one>true</has_one>
    <one_column>2</one_column>
    <has_two>true</has_two>
    <two_column>12</two_column>
    </client

I've looked through other answers, and I've tried various solutions. This one works, but only for the first client, all others are unaffected:

        XDocument doc = XDocument.Load(@"c:/xmlconfig/sample.xml");
        doc.Root.Element("client").Add(new XElement("testing", "none"));

I tried adding a foreach loop and it adds a testing element for each client node, but it adds all of them to the first entry and all the rest are untouched.

     XDocument doc = XDocument.Load(@"c:/xmlconfig/miss.xml");
    foreach (var client in doc.Descendants("client"))
    {
        doc.Root.Element("client").Add(new XElement("testing", "none"));
    }

Where am I missing something?

Upvotes: 1

Views: 3008

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

You should add new element to each client:

XDocument doc = XDocument.Load(@"c:/xmlconfig/miss.xml");
foreach (var client in doc.Descendants("client"))
{
    // use current client
    client.Add(new XElement("testing", "none"));
}

Lets look what happens here:

foreach (var client in doc.Descendants("client"))
{
    doc.Root.Element("client").Add(new XElement("testing", "none"));
}

For each client you execute query which takes first client element under root. Then new element added to this first client. This is repeated so many times, as number of clients in xml. And you end up testing element added to first client N times.

Upvotes: 4

Related Questions