Overview:
LINQ to XML (hereinafter referred to as LTX) is Microsoft's curd for XML based on LINQ technology. It is easier to use than the XML operation in System.Xml. This time use it in the company upgraded the boss's mail system, quite a bit of experience, now summed up.
Main objects:
1.xdocument:xml Document object loaded in XML document according to its static method: XDocument XDoc = Xdocument.load (@ "**xml path * *")
. Element ("NodeName") obtains the child node XElement object, Xdoc is usually the root node
. Sava ("Xmlpath") Save the document to an XML file
XElement Xele = xdoctypedef.element ("root"). Elements (). Where (P = = P.attribute ("Name"). Value = = strtopname). Single ();
2.XElement: Node Object
. Element ("NodeName") Gets the child node XElement object
. Elements () returns a collection of child nodes
. Elements ("NodeName") returns a collection of child nodes whose name is "NodeName"
. Add (param[] obj) can be increased by multiple nodes or attributes
. Remove () deletes the node.
. Value Node Properties
3.XAttribute: Property Object
Knowing this makes it possible to manipulate XML in conjunction with LINQ.
The following is a partial source code that adds child nodes and attributes to a node in a recent small project:
1 Public Static BOOLAddElement (XElement Xelenode,stringAddeletype,stringStrcontralname,stringstrcontent)2 {3XElement Xelechild =NewXElement (addeletype);4Xelechild.add (NewXAttribute (strcontralname,strcontent));5 //There's a wood. This child control6 if(Xelenode.elements (). Count () >0&& xelenode.elements (). Where (p = p.attribute (strcontralname). Value = = strcontent). Count () >0)7 return false;8 Xelenode.add (xelechild);9 Ten return true; One A } - - Public Static BOOLAddattr (XElement Xelenode, dictionary<string,string>dic) the { - BOOLFlag =true; - foreach(keyvaluepair<string,string> Pairinchdic) - { + if(Xelenode.elements (). Where (p = p.attribute ("Name"). Value = = pair. Key). Count () >0) - { +Flag =false; A Continue; at } -XElement Xelechild =NewXElement ("Attribute"); -Xelechild.add (NewXAttribute ("Name", pair. Key.tostring ())); -Xelechild.value =pair. Value.tostring (); - Xelenode.add (xelechild); - } in returnFlag; -}
View Code
deleting and modifying nodes
...//Modify NodeXElement Xele = xelefirstnode.elements (). Where (p = p.attribute ("Name"). Value = = strcontralname). Single () asXElement; Xele= Xele. Elements (). Where (p = p.attribute ("Name"). Value = = strattr). Single () asXElement; Xele. Value=Strattrdes; Xdoc.save (strpath);//del nodeif(MessageBox.Show ("Confirm Delete?","Warning", Messageboxbuttons.yesno, messageboxicon.warning) = =dialogresult.no)return; foreach(ObjectStrinchLbatrributes.selecteditems)//ListBox Mutiselect { stringStrattr =Str. ToString (); XElement xeleattr= Xelesecondnode.elements (). Where (p = p.attribute ("Name"). Value = = strattr). Single () asXElement; Xeleattr.remove (); } xdoc.save (strpath);
Practice to Master.
Linq Learning Summary 2--linq to XML