1

I'm new in C# and I have tried everything during days and days but I have no answers to solve my problem.

I have a xml doc like this that populate a treeview in a windows form app:

<?xml version="1.0" encoding="utf-8" ?>
<root>
<folder title='Standard Elements'>
  <folder title='Screw' >
    <folder title='Type 1' >
      <record title='DIN EN ISO 4762' />
      <record title='DIN EN ISO 7964' />
      <record title='DIN EN ISO 21269' />
    </folder>
    <folder title='Type 2' >
      <record title='DIN EN ISO 4026' />
      <record title='DIN EN ISO 4027' />
      <record title='DIN EN ISO 4028' />
    </folder>
    <folder title='Type 3' >
      <record title='DIN EN ISO 4014' />
      <record title='DIN EN ISO 4017' />
      <record title='DIN EN ISO 4762' />
      <record title='DIN EN ISO 24015' />
    </folder>
  </folder>
  <folder title='Bearing' >
  </folder>
  <folder title='Pin' >
  </folder>
</folder>
  <folder title='Shaft' >
  </folder>
</root>

I have to include a new element below the node with title "Type 2" or other specified node. I'm using Linq in my application but I have no idea to to handle this ensue.

2 Answers 2

1

try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement type2 = doc.Descendants("folder").Where(x => (string)x.Attribute("title") == "Type 2").FirstOrDefault();

            type2.Add(new XElement("record", new XAttribute("title", "DIN EN ISO 4029")));
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's worked perfect. Actually I feel stupid now. Thanks for the answer.
1

You can use XMLDocument type provided by the framework. Select the node you need, create a new node object and add it as a child to your selected node.

Your question is similar to this: Modify XML existing content in C#

1 Comment

If I understood right to use that solution I would have to modify the structure of my XML file that I'm not able to do because I receive the file from other application. I have to find the node with the attribute "Type 2" and add a new node in it.

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.