CSharp - Adding a Node in the Specified Node's Child Nodes with AddBeforeSelf

Description

Adding a Node in the Specified Node's Child Nodes with AddBeforeSelf

Demo

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

class Program/*from  w w w .  j a v a2 s.  c o m*/
{
    static void Main(string[] args){
        //  A document with one book participant.
        XDocument xDocument = new XDocument(
          new XElement("Books",
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "Joe"),
              new XElement("LastName", "Ruby"))));
        
        xDocument.Element("Books").Add(
          new XElement("Book",
            new XAttribute("type", "Editor"),
            new XElement("FirstName", "PHP"),
            new XElement("LastName", "Python")));
        
        xDocument.Element("Books").
          Elements("Book").
          Where(e => ((string)e.Element("FirstName")) == "PHP").
          Single<XElement>().AddBeforeSelf(
            new XElement("Book",
              new XAttribute("type", "Technical Reviewer"),
              new XElement("FirstName", "Fabio"),
              new XElement("LastName", "Ferracchiati")));
        
        Console.WriteLine(xDocument);
    }
}

Result

Related Topic