CSharp - Adding Processing Instructions After the Document is created

Description

Adding Processing Instructions After the Document is created

Demo

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

class Program//  ww  w  .  j  a va 2  s  .c  o  m
{
    static void Main(string[] args){
              XDocument xDocument =
                new XDocument(new XElement("Books",
                                           new XElement("Book",
                                                        new XElement("FirstName", "Joe"),
                                                        new XElement("LastName", "Ruby"))));
        
        XProcessingInstruction xPI1 = new XProcessingInstruction("BookCataloger",
                                                                 "out-of-print");
        xDocument.AddFirst(xPI1);
        
        XProcessingInstruction xPI2 = new XProcessingInstruction("ParticipantDeleter",
                                                                 "delete");
        XElement outOfPrintParticipant = xDocument
          .Element("Books")
          .Elements("Book")
          .Where(e => ((string)((XElement)e).Element("FirstName")) == "Joe"
                   && ((string)((XElement)e).Element("LastName")) == "Ruby")
          .Single<XElement>();
        
        outOfPrintParticipant.AddFirst(xPI2);
        
        Console.WriteLine(xDocument);
    }
}

Result

Related Topic