C# Use Linq to implement the basic operation of Xml file (create xml file, add and delete xml file node information)

1 private static void GetXmlNodeInforOld( string xmlPath) 2 { 3 try 4 { 5 XDocument myXDoc = XDocument.Load(xmlPath); 6 XElement rootNode = myXDoc.Element( " Users " ); 7 foreach (XElement node in rootNode.Elements( " User " )) 8 { 9 Console.WriteLine( " User ID = {0} " , node.Attribute( " ID " ).Value); 10 11 string name = node.Element( " name " ).Value; 12 string password = node.Element( " password " ).Value; 13 string description = node.Element( " description " ).Value; 14 Console.WriteLine( " name = {0} \npassword = {1} \ndescription = {2} " , name, password, description); 15 } 16 } 17 catch (Exception ex) 18 { 19 Console.WriteLine(ex.ToString()); 20 } 21 } 22 23 private static void GetXmlNodeInformation( string xmlPath) 24 { 25 try 26 { 27 // definition and load node (root node) from xml file 28 XElement rootNode = XElement.Load(xmlPath); 29 // Query statement: Get root The name child node under the node (the child node at this time can cross the hierarchy: grandchild node, grandchild node...) 30 IEnumerable < XElement > targetNodes = from target in rootNode.Descendants( " name " ) 31 select target; 32 foreach (XElement node in targetNodes) 33 { 34 Console.WriteLine( " name = {0} " , node.Value); 35 } 36 37 // Query statement: Get all the User whose ID attribute value is equal to "111111" and the function child node Node (parallel condition is connected with "&&" symbol) 38 IEnumerable < XElement > myTargetNodes = from myTarget in rootNode.Descendants( " User " ) 39 where myTarget.Attribute( " ID " ).Value.Equals( " 111111 " ) && myTarget.HasElements 40 select myTarget; 41 foreach (XElement node in myTargetNodes) 42 { 43 Console.WriteLine( " name = {0} " , node.Element( " name " ).Value); 44 Console.WriteLine( " password = {0} " , node.Element( " password " ).Value); 45 Console.WriteLine( " description = {0} " , node.Element( " description " ).Value); 46 } 47 } 48 catch (Exception ex) 49 { 50 Console.WriteLine(ex.ToString()); 51 } 52 }