1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Argh. I knew it was something simple. I hate learning curves. That worked nicely, thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.