First, read the contents of the XML file:
#region"Get XML file Contents"//load the XML file inXDocument Xdoc = Xdocument.load ("f:\\6.2 \\DelegateExample\\XmlConsole\\XMLFile.xml"); //get XML root element operationXElement root =Xdoc. Root; XElement Elem= root. Element (" Book"); //get the value of the name tagXElement name = Elem. Element ("name1"); Console.WriteLine (name. Value); Console.WriteLine ("------------------------"); //gets all child elements under the root elementienumerable<xelement> element =Root. Elements (); foreach(XElement IteminchElement) { foreach(XElement item1inchitem. Elements ()) {Console.WriteLine (item1. Value); } Console.WriteLine ("------------------------"); Console.WriteLine (item. Attribute ("ID"). Value); Console.readkey (); } #endregion
Second, write the XML content:
//get root node elementXDocument XDocument =NewXDocument (); XElement Roo=NewXElement ("b"); XElement Root2=NewXElement (" Book",NewXElement ("Name3","3333",NewXAttribute ("ID","3"))); XElement name1=NewXElement ("name1"); XElement ROOT3=NewXElement ("Student"); Root2. Setelementvalue ("name1","1111"); Root2. Setelementvalue ("name2","2222"); Root3. Setattributevalue ("Student1","33333"); Root3. Setelementvalue ("Student2","44444"); Roo. ADD (NAME1); Roo. ADD (ROOT2); Roo. ADD (ROOT3); Roo. Save ("D://xmlfile.xml"); Console.readkey ();
Thirdly, XMLNode is an abstract class, which provides some methods for manipulating nodes.
//take root node. varroot = xmldoc.documentelement;//take the root node.//to take a specified single node .XmlNode Oldchild = Xmldoc.selectsinglenode ("Bookstore/newbook"); //takes a collection of specified nodesXmlNodeList nodes = Xmldoc.selectnodes ("Bookstore/newbook"); //fetch all XML nodes .XmlNodeList nodelist = Xmldoc.getelementsbytagname ("*");
Add, delete (remove), modify node and attribute Setattributevalue () + Save (),
removechild --Removing nodes RemoveAttribute--Removing attributes
V. LINQ to XML (XML additions and deletions)
C # XML Class learning finishing (backlog)