The core class XElement of LINQ to XML, a XElement represents a node, new XElement ("Order"), create a label named order, call Add Add child node, also XElement Object!
The following are common forms of several LINQ operations XML.
Write a file (Generate node Nature)
The code is as follows |
Copy Code |
XElement epersons = new XElement ("Persons"); XElement ptom = new XElement ("person"); Add a person node Ptom. Add (New XElement ("Name", "Tom"))//Add child nodes under Ptom Ptom. ADD (New XElement ("Age", "18")); Epersons.add (Ptom); XElement pjack = new XElement ("person"); Pjack. ADD (New XElement ("Name", "Jack")); Pjack. ADD (New XElement ("Age", "20")); Epersons.add (Pjack); |
Final Build:
The code is as follows |
Copy Code |
<?xml version= "1.0" encoding= "Utf-8"?> <Persons> <Person> <Name>Tom</Name> <Age>18</Age> </Person> <Person> <Name>Jack</Name> <Age>20</Age> </Person> </Persons> |
Write file (Generate attribute property)
XElement ptom = new XElement ("person");
The code is as follows |
Copy Code |
Ptom. Add (New XAttribute ("Name", "Tom");//Add XAttribute to generate property Ptom. ADD (New XAttribute ("Age", "18")); Epersons.add (Ptom); XElement pjack = new XElement ("person"); Pjack. ADD (New XAttribute ("Name", "Jack")); Pjack. ADD (New XAttribute ("Age", "20")); Epersons.add (Pjack); |
Final Build:
The code is as follows |
Copy Code |
<Persons> <person name= "Tom" age= "a"/> <person name= "Jack" age= "/>" </Persons> |
Read the value of the XML read node format
code is as follows |
copy code |
XDocument xd= xdocument.load ("XML file Address"); foreach ( XElement item in XD. Root.descendants ("person")//Get every person node, get this node and fetch his name the value of this node { Console.WriteLine (item. Element ("Age"). Value); The bottom node of the//person node is name } |
Note: Doc.root (Gets the XElement object of the root node). The XElement ("TagName") method gets the node whose first name is tagname under the node. If Doc.root. xelements (plural form) is to get all the child nodes, descendants ("TagName") descendants node
Read the value of the XML read attribute format
code is as follows |
copy code |
XDocument xd= xdocument.load (@ "D:program filesdemodemoconsoleapplication2xmlfile2.xml"); foreach (XElement item in XD. Root.descendants ("person")//Get every person node, get this node and fetch his name the value of this node { Console.WriteLine (item. Attribute ("Age"). Value); The bottom node of the//person node is name } |