Background:
In the work, learning and using the OPC server/client system, found that the development of the design structure is the device plc taglist written as an XML file, when the program starts to load to complete the automatic configuration.
Thus began the C # ASP. Learn about XML files in the. Net.
Study notes:
1> Brief Description:
XML is an Extensible markup language that uses elements and attributes to describe data.
C # uses XML benefits:
A. In fact, it is a common data format for program interaction, regardless of the language written by the program can exchange data through XML, meaning that C # objects can communicate with a Java object;
B. Can be used as a means of storing data, equivalent to a small data source, as a configuration file, than. ini excellent and easy to use. Fixed format, easy to modify.
2>xml Common operations:
Name space
Using System.Xml;
Initializing an XML instance
XmlDocument xml=new XmlDocument ();
Imports the specified XML file XML. Load (path);
Xmldoc.load (AppDomain.CurrentDomain.BaseDirectory + "\" + xmlfile);
Specify a node
XmlNode Root=xml. selectSingleNode ("/root");
Get all immediate child nodes under a node
XmlNodeList Childlist=root. ChildNodes;
Determine if there are child nodes under the node
Root. HasChildNodes;
Gets a collection of sibling nodes with the same name
XmlNodeList Nodelist=xml. SelectNodes ("/root/news");
Generate a new node
XmlElement Node=xml. CreateElement ("News");
Adds a node to the specified node as its child node
Root. AppendChild (node);
Before adding a node to a child node under a specified node
Root. InsertBefore (Node,root. Childenodes[i]);
Creates a new property for the specified node and assigns a value
Node. SetAttribute ("id", "11111");
To add a child node to a specified node
Root. AppendChild (node);
Gets the specified property value for the specified node
String Id=node. attributes["id"]. Value;
Gets the text in the specified node
String Content=node. InnerText;
Save the XML file
Xml. Save (path);
3> How to write data from WinForm to XML file
The individual is summarized as dynamic write and static write, can be directly in the program hard-coding XML element of each node, also can get write from text,
You can also read from the database (the OPC s/c system reads taglist from the OPC server to the dataset and then save the number of XML) to the dataset and then write the XML file.
The following exercise code belongs to the second type:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Xml;usingSystem.IO;//FileStreamnamespacewinform_createxml{ Public Partial classForm1:form {Private stringxmlfile; XmlDocument xmldoc=NewXmlDocument (); PublicXmlNode Root; PublicForm1 () {InitializeComponent (); } Private voidForm1_Load (Objectsender, EventArgs e) {xmlfile="Test.xml"; //Creating an XML fileCreatexml (xmlfile); } /// <summary> ///functions for creating XML Files/// </summary> /// <param name= "FileName" ></param> Public Static voidCreatexml (stringFileName) { stringDataPath =AppDomain.CurrentDomain.BaseDirectory; FileStream objFileStream=NULL; StreamWriter objStreamWriter=NULL; Try { //determine if the file exists and overwrite it if it exists if(File.exists (datapath+FileName)) { return; } objFileStream=NewFileStream (datapath+filename,filemode.append,fileaccess.write); objStreamWriter=NewStreamWriter (Objfilestream,encoding.default); Objstreamwriter.writeline ("<?xml version=\ "1.0\" encoding=\ "utf-8\"?>"); Objstreamwriter.writeline ("<root>\r\n</root>");//writing a string to a file } Catch(Exception ex) {}finally { if(objStreamWriter! =NULL) {Objstreamwriter.flush ();//Cleanup BufferObjstreamwriter.close ();//closing objects and underlying streams } } } /// <summary> ///Add a function for node XmlNode/// </summary> Public voidAddNode () {XmlNode WebSite= Xmldoc.createelement ("WebSite"); XmlAttribute sitename1= Xmldoc.createattribute ("SiteName"); Sitename1. Value=SiteName. Text.trim (); WebSite.Attributes.Append (SITENAME1); Website.innertext=SiteName. Text.trim (); XmlAttribute SITEURL1= Xmldoc.createattribute ("SiteURL"); Siteurl1. Value=SiteURL. Text.trim (); WebSite.Attributes.Append (SITEURL1); Xmldoc.load (AppDomain.CurrentDomain.BaseDirectory+"\\"+ xmlfile);//* * * You must first open the XML file * * *Root= Xmldoc.selectsinglenode ("Root");//Select the first XmlNode to match//root = Xmldoc.getelementbyid ("root");Root. AppendChild (WebSite); Xmldoc.appendchild (root); Xmldoc.save (xmlfile); } Private voidButton1_Click (Objectsender, EventArgs e) { //AddNode ();Checknode (); MessageBox.Show ("please look at the XML under the current path! "); } /// <summary> ///Check the SiteName entered at the site name if there is a change in the node, modify the Siturl of this node if it does not exist/// </summary> Public voidChecknode () {intj =0; Xmldoc.load (AppDomain.CurrentDomain.BaseDirectory+"\\"+ xmlfile);//* * * You must first open the XML file * * *XmlNodeList nodelist = Xmldoc.selectsinglenode ("Root"). ChildNodes;//get all child nodes of root root node foreach(XmlNode xninchnodelist) {XmlElement XE= (XmlElement) xn;//Converting a node type to a XmlElement type if(XE. GetAttribute ("SiteName")==SiteName. Text.trim ()) {J=1; Xe. SetAttribute ("SiteURL", SiteURL. Text.trim ()); Break;//end the entire loop body, continue is the end of a single cycle } } if(J = =0) {AddNode (); MessageBox.Show ("Add Success"); } Else{xmldoc.save (xmlfile); MessageBox.Show ("Modification succeeded"); } } /// <summary> ///Delete the node in the SiteName text box that already exists for this site name in the XML node/// </summary> /// <param name= "Sender" ></param> /// <param name= "E" ></param> Private voidButton2_Click (Objectsender, EventArgs e) {Xmldoc.load (AppDomain.CurrentDomain.BaseDirectory+"\\"+ xmlfile);//* * * You must first open the XML file * * *Root = Xmldoc.selectsinglenode ("Root"); XmlNodeList nodelist= Xmldoc.selectsinglenode ("Root"). ChildNodes;//Get all child nodes foreach(XmlNode xninchnodelist) {XmlElement XE=(XmlElement) xn; if(XE. GetAttribute ("SiteName")==SiteName. Text.trim ()) {root. RemoveChild (XE); Break; }} xmldoc.save (XMLFile); MessageBox.Show ("Delete succeeded"); } }}
Note: Although the landlord novice, this article original, such as reproduced please indicate the original author, thank you!
We study together ~
C # Winform--xml file