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//from w  w  w .ja  va  2 s. c  om
{
    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