Csharp/C Sharp/XML LINQ/XElement Update
Updating a Node"s Value
<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {
public static void Main() { 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", "J"), new XElement("LastName", "R")))); Console.WriteLine(xDocument); firstParticipant.Element("FirstName").Value = "J"; firstParticipant.Nodes().OfType<XComment>().Single().Value ="LINQ"; ((XElement)firstParticipant.Element("FirstName").NextNode).Nodes().OfType<XText>().Single().Value = "R"; Console.WriteLine(xDocument); }
}
</source>
Updating a Processing Instruction
<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {
public static void Main() { XProcessingInstruction procInst; XDocument xDocument = new XDocument( new XElement("Books"), procInst = new XProcessingInstruction("Book", "out-of-print")); Console.WriteLine(xDocument); procInst.Target = "BookContactManager"; procInst.Data = "update"; Console.WriteLine(xDocument); }
}
</source>
Updating the Document Type
<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; public class MainClass {
public static void Main() { XDocumentType docType; XDocument xDocument = new XDocument(docType = new XDocumentType("Books", null,"Books.dtd", null), new XElement("Books")); Console.WriteLine("Before updating document type:"); Console.WriteLine(xDocument); docType.Name = "MyBooks"; docType.SystemId = "http://www.yoursite.ru/DTDs/MyBooks.DTD"; docType.PublicId = "-//DTDs//TEXT Book Participants//EN"; Console.WriteLine(xDocument); }
}
</source>