usingSystem;usingSystem.Xml.Linq;namespacesample2{classProgram {Static voidMain (string[] args) { #regionWrite file One (generation node nature)XDocument Xdoc=NewXDocument (); XElement Persons=NewXElement ("Persons"); XElement Peorson1=NewXElement (" Person");//Add a person nodePeorson1.add (NewXElement ("Name","Tom"));//Add a child node under PtomPeorson1.add (NewXElement (" Age"," -")); Persons.add (Peorson1); XElement Person2=NewXElement (" Person"); Person2.add (NewXElement ("Name","Jack")); Person2.add (NewXElement (" Age"," -")); Persons.add (Person2); Xdoc. ADD (Persons);//Add the root element to the documentXdoc. Save ("Myxml1.xml");//SaveConsole.WriteLine ("The XML file was created successfully! "); Console.ReadLine (); /*generate Myxml.xml content as follows * <?xml version= "1.0" encoding= "Utf-8"?> <perso ns> <Person> <Name>Tom</Name> <age>18< ;/age> </Person> <Person> <name>jack</name> ; <Age>20</Age> </Person> </Persons>*/ #endregion #regionRead the value of the XML read node formatXDocument xd= Xdocument.load ("Myxml1.xml"); foreach(XElement IteminchXd. Root.descendants (" Person"))//get each person node, get this node and then fetch the value of this node of his name{Console.WriteLine ("name: {0} Age: {1}", item. Element ("Name"). Value, item. Element (" Age"). Value);//The node of the person is the node of name} console.readline (); #endregion #regionWrite file two (Generate attribute properties)XDocument Xdoc1=NewXDocument (); XElement Pers=NewXElement ("Persons"); XElement P1=NewXElement (" Person"); P1. ADD (NewXAttribute ("Name","Tom"));//add XAttribute to generate propertiesP1. ADD (NewXAttribute (" Age"," -")); Pers.add (p1); XElement P2=NewXElement (" Person"); P2. ADD (NewXAttribute ("Name","Jack")); P2. ADD (NewXAttribute (" Age"," -")); Pers.add (p2); Xdoc1. ADD (Pers);//Add the root element to the documentXdoc1. Save ("Myxml2.xml");//SaveConsole.WriteLine ("XML file two build succeeded! "); Console.ReadLine (); /*generate Myxml.xml content as follows * <?xml version= "1.0" encoding= "Utf-8"?> <perso Ns> <person name= "Tom" age= "/> <person name=" Jack "age="/> " </Persons>*/ #endregion #regionRead the value of the XML read attribute formatXDocument Xd1= Xdocument.load ("Myxml2.xml"); foreach(XElement IteminchXd1. Root.descendants (" Person"))//get each person node, get this node and then fetch the value of this node of his name{Console.WriteLine ("name: {0} Age: {1}", item. Attribute ("Name"). Value, item. Attribute (" Age"). Value);//The node of the person is the node of name} console.readline (); #endregion } }}
C # using LINQ to XML read XML,LINQ build xml,linq create with attributes or with node XML