Example Analysis of basic Operation of XML document
This article will explain in detail the sample analysis of the basic operation of XML documents. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
1. Brief introduction
Using System.Xml;// initializes a xml instance XmlDocument xml=new XmlDocument (); / / imports the specified xml file xml.Load (path); xml.Load (HttpContext.Current.Server.MapPath ("~ / file/bookstore.xml")); / / specifies a node XmlNode root=xml.SelectSingleNode ("/ root"); / / gets all the direct child nodes under the node XmlNodeList childlist=root.ChildNodes;// to determine whether there is a child node root.HasChildNodes under that node / / get a collection of peer nodes with the same name XmlNodeList nodelist=xml.SelectNodes ("/ Root/News"); / / generate a new node XmlElement node=xml.CreateElement ("News"); / / add a node to the specified node as its child node root.AppendChild (node); / / add the node to a child node under the specified node before root.InsertBefore (node,root.ChildeNodes [I]); / / assign the new attribute of the specified node and assign the value node.SetAttribute ("id", "11111") / / add a child node root.AppendChild (node) for the specified node; / / get the specified attribute value of the specified node string id=node.Attributes ["id"] .Value;// gets the text string content=node.InnerText;// in the specified node to save the XML file string path=Server.MapPath ("~ / file/bookstore.xml"); xml.Save (path); / / or use: xml.Save (HttpContext.Current.Server.MapPath ("~ / file/bookstore.xml"))
How to operate XML in C#.net
Namespaces that need to be added:
Define several public objects: XmlDocument xmldoc; XmlNode xmlnode; XmlElement xmlelem
1. Create a xml file under the server directory with the same name:
Method 1:
Xmldoc = new XmlDocument (); / / add the declarative paragraph of XML, XmlDeclaration xmldecl;xmldecl = xmldoc.CreateXmlDeclaration ("1. 0", "gb2312", null); xmldoc.AppendChild (xmldecl); / / add a root element xmlelem = xmldoc.CreateElement ("", "Employees", ""); xmldoc.AppendChild (xmlelem); / / add another element for