Xml
XmlTextReader provides only forward, fast, and read-only reading of xml content. xml larger than 1 MB is often used for reading, XmlTextReader. Create () loads xml files
XmlDocument reads xml content to the memory. The XmlDocument. Load () method loads the file in the shared read mode.
XDocument is used by Linq to Xml, which is similar to XmlDocument, but has better performance than XmlDocument.
Basic operations on Linq to Xml
// Load the xml document
XDocument xDocument = XDocument. Load (Server. MapPath (@ "test. xml "));
// Obtain the root element
XElement root = xDocument. Root;
// Obtain the element based on the element name
XElement element = xDocument. Descendants ("Class"). First ();
// Obtain the element based on the element property value (determine whether it is null first)
XElement element2 = xDocument. Descendants (). First (m => m. Attribute ("Name ")! = Null & m. Attribute ("Name"). Value = "Computer ");
// Obtain the element based on the element value
XElement element3 = xDocument. Descendants (). First (m => m. Value = "Mr. Yang ");
// Obtain some elements based on the element name
List <XElement> elements = xDocument. Descendants ("Class"). ToList ();
// Obtain certain elements based on the element property value (determine whether the element is null first)
List <XElement> elements2 = xDocument. Descendants (). Where (m => m. Attribute ("Name ")! = Null & m. Attribute ("Name"). Value = "Computer"). ToList ();
// Obtain some elements based on their values.
List <XElement> elements3 = xDocument. Descendants (). Where (m => m. Value = "Mr. Yang"). ToList ();
// If the element does not have a child element, add it.
Element. SetElementValue ("Code", "101 ");
// Update if the element has child elements
Element. SetElementValue ("Teacher", "Miss Yang ");
// Delete the child element
Element. Element ("Code"). Remove ();
// Modify the element value
Element. Value = "abcdf ";
// If an attribute exists, the attribute value is modified.
Element. SetAttributeValue ("Name", "English ");
// If the property does not exist, add the property
Element. SetAttributeValue ("Code", "101 ");
// Delete the owner
Element. Attribute ("Name"). Remove ();
// Delete an element
Element. Remove ();
// Save the modification to the document
// XDocument. Save (Server. MapPath (@ "test. xml "));
Note: Descendants can traverse all the subnodes under a node or document, while Elements can traverse the subnodes at the current node or the next level of the document.