Search code examples
c#xmllinqxelement

how to add a child node inside a nother child node


How do I add another concept node (Concept Key="1234"R) to the child Rssd node where rssd = 3284070 in C#, I'm using XElements to contruct all the XML. Do I need a linq statement?

<Root>
 <Rssd Key="3900455" />
 <Rssd Key="4442961" />
 <Rssd Key="4442961" />
 <Rssd Key="4442970" />
 <Rssd Key="3284070">
   <Concept Key="1662">
   <Concept Key="1668">
 </Rssd>
</Root>

Solution

  • LINQ is only used to query (to select a part of the dataset), not to modify the dataset. Here, I use it to get the Rssd element where we want to add the new Concept element.

    XDocument xDocument = ...
    
    XElement parentElement = (from rssdElement in xDocument.Descendants("Rssd")      // Iterates through the collection of all Rssd elements in the document
                              where rssdElement.Attribute("Key").Value == "3284070"  // Filters the elements to get only those which have the correct Key attribute value
                              select rssdElement).FirstOrDefault();                  // Gets the first element that satisfy the above condition (returns null if no element has been found)
    
    if (parentElement == null)
        throw new InvalidDataException("No Rssd element found with the key \"3284070\"");
    
    XElement newConceptElement = new XElement("Concept");  // Creates a new Concept element
    newConceptElement.Add(new Attribute("Key", "1234"));   // Adds an Key attribute to the element with the specified value
    
    parentElement.Add(newConceptElement);                  // Adds the new Concept element to the Rssd element