XDocument xDocument = new XDocument(<br /> new XElement("BookParticipants", firstParticipant =<br /> new XElement("BookParticipant",<br /> new XComment("This is a new author."),<br /> new XAttribute("type", "Author"),<br /> new XElement("FirstName", "Joe"),<br /> new XElement("LastName", "Rattz")))); </p><p>Console.WriteLine("Before updating nodes:");<br />Console.WriteLine(xDocument); </p><p>// Now, lets update an element, a comment, and a text node.<br />firstParticipant.Element("FirstName").Value = "Joey";<br />firstParticipant.Nodes().OfType<XComment>().Single().Value =<br /> "Author of Pro LINQ: Language Integrated Query in C# 2008.";<br />((XElement)firstParticipant.Element("FirstName").NextNode)<br /> .Nodes().OfType<XText>().Single().Value = "Rattz, Jr."; </p><p>Console.WriteLine("After updating nodes:");<br />Console.WriteLine(xDocument);
輸出
Before updating nodes:<br /><BookParticipants><br /> <BookParticipant type="Author"><br /> <!--This is a new author.--><br /> <FirstName>Joe</FirstName><br /> <LastName>Rattz</LastName><br /> </BookParticipant><br /></BookParticipants><br />After updating nodes:<br /><BookParticipants><br /> <BookParticipant type="Author"><br /> <!--Author of Pro LINQ: Language Integrated Query in C# 2008.--><br /> <FirstName>Joey</FirstName><br /> <LastName>Rattz, Jr.</LastName><br /> </BookParticipant><br /></BookParticipants>