Description

Updating a Node's Value

Demo

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

class Program/*ww w .j a v  a 2  s .  c  o m*/
{
    static void Main(string[] args){
        //  we will use this to reference to one of the elements in the XML tree.
        XElement firstParticipant;
        
        XDocument xDocument = new XDocument(
          new XElement("Books", firstParticipant =
            new XElement("Book",
              new XComment("This is a new author."),
              new XAttribute("type", "Author"),
              new XElement("FirstName", "Joe"),
              new XElement("LastName", "Ruby"))));
        
        Console.WriteLine("Before updating nodes:");
        Console.WriteLine(xDocument);
        
        //  Now, lets update an element, a comment, and a text node.
        firstParticipant.Element("FirstName").Value = "Joey";
        firstParticipant.Nodes().OfType<XComment>().Single().Value =
          "Author of Pro LINQ: Language Integrated Query in C# 2008.";
        ((XElement)firstParticipant.Element("FirstName").NextNode)
          .Nodes().OfType<XText>().Single().Value = "Ruby, Jr.";
        
        Console.WriteLine("After updating nodes:");
        Console.WriteLine(xDocument);
    }
}

Result

Related Topic