XElement is the core class of LinqToXML. an XElement represents a node. newXElement (& quot; Order & quot;) creates a label named "Order" and calls "Add" to Add subnodes. it is also an XElement object! The core class XElement of Linq To XML. an XElement represents a node, new XElement ("Order"), creates a label named "Order", and calls Add To Add subnodes, which is also an XElement object!
Below are some common forms of XML operations for LINQ.
/// Write the file (generate the node type)
XElement ePersons = new XElement ("Persons"); XElement ptom = new XElement ("Person"); // add a Person node ptom. add (new XElement ("Name", "Tom"); // Add the child node ptom under 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 generation:
Tom18Jack20
/// Write a file (generating attribute attributes)
XElement ptom = new XElement ("Person"); ptom. add (new XAttribute ("Name", "tom"); // Add XAttribute to generate the 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 generation:
// Read the value of the node format in XML format
XDocument xd = XDocument. load ("XML file address"); foreach (XElement item in xd. root. descendants ("Person") // obtain the value of each Person node, and then obtain the value of this node whose Name is {Console. writeLine (item. element ("Age "). value); // Name of the node under the Person node} Note: doc. root (get the XElement object of the root node ). the XElement ("tagname") method obtains the first node named tagname under the node. If doc. root. XElements (plural form) is to get all the child nodes, Descendants ("" tagname "") child nodes
// Read the value of the attribute format in XML.
XDocument xd = XDocument. load (@ "D: \ Program Files \ Demo \ ConsoleApplication2 \ XMLFile2.xml"); foreach (XElement item in xd. root. descendants ("Person") // obtain the value of each Person node, and then obtain the value of this node whose Name is {Console. writeLine (item. attribute ("Age "). value); // Name of the node under the Person node}
The above is a detailed description of the sample code for reading XML by Linq. For more information, see other related articles in the first PHP community!