using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq; using System.Reflection; using System.Xml.Linq; class Program { static void Main(string[] args) { string doc = @"<people> <!-- Employee section --> <person> <id>1</id> <firstname>C</firstname> <lastname>L</lastname> <idrole>1</idrole> </person> </people>"; XElement xml = XElement.Parse(doc); Console.WriteLine(xml); } }
XML LINQ
Creating an Element Using the First Prototype
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 firstName = new XElement("FirstName", "Joe"); Console.WriteLine((string)firstName); } }
Casting a Node to a Different Data Type Than Its Value's Original Data Type
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 smoker = new XElement("Smoker", "true"); Console.WriteLine(smoker); Console.WriteLine((bool)smoker); } }
Different Node Value Types Retrieved via Casting to the Node Value's Type
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 count = new XElement("Count", 12); Console.WriteLine(count); Console.WriteLine((int)count); XElement smoker = new XElement("Smoker", false); Console.WriteLine(smoker); Console.WriteLine((bool)smoker); XElement pi = new XElement("Pi", 3.1415926535); Console.WriteLine(pi); Console.WriteLine((double)pi); } }
Casting an Element to Its Value's Data Type Outputs the Value
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 name = new XElement("Name", "Joe"); Console.WriteLine(name); Console.WriteLine((string)name); } }
Immediate Execution of the XML Tree Construction
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() { string[] names = { "J", "P", "G", "P" }; XElement xNames = new XElement("Beatles", from n in names select new XElement("Name", n)); names[3] = "R"; Console.WriteLine(xNames); } }
Calling the ToString Method on an Element Produces the XML Tree
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 name = new XElement("Name", "Joe"); Console.WriteLine(name.ToString()); } }