C# writes to xml file
1、XmlDocument
1. I think it is the most primitive and basic one: use XmlDocument to write nodes to an XML file, and then use XmlDocument to save the file.
First, load the XML file to be written, but if there is no, it needs to be created. During the new creation process, there must be written code;
XmlDocument doc = new XmlDocument(); try { (""); } catch { XmlTextWriter xtw = new XmlTextWriter("", Encoding.UTF8); // Create a new XML file (); ("gnode"); // gnode root node ("myxm1"); // The element myxmls under the root node of gnode (); (); (); (); (""); } XmlNode xn = ; //Find the root node XmlElement xe = ("myxml2"); //Create an element under the root node. If it is an attribute, use XmlAttribute; = "Salary Code hahaha"; //Write text node (value) to child nodes (xe); //The root node will include it in (""); //Save the file using XmlDocument }
Note: When creating a new root node, WriteStartElement can only be nested, which means there can only be one root node.
2. The value in the DataSet object is used to generate an XML file
Apply to the database, and use the values in the database DataSet object to generate elements of the XML file;
using (SqlConnection con = new SqlConnection("Server=.;DataBase=HGSTUDY;uid=sa;pwd=yao")) { (); SqlCommand command = new SqlCommand("select * from GL_STUDY", con); = ; DataSet ds = new DataSet("DATASET"); //DATASET will become the root node name in the XML file, otherwise the system will name it NewDataSet SqlDataAdapter sda = new SqlDataAdapter(); = command; (ds, "DATATABLE"); //DATATABLE is the child node name in the generated XML file, otherwise the system will name it Table. (""); // DataSet method WriteXml writes data to XML file, that's the sentence. If not saved to the file, directly () }
3. Use XmlSerializer to convert the attribute value of the class to the element value of the XML file.
Use a string as an XMLAttribute or xmlElement in an XML document. [Its elements or attributes are set by the definition of the class (xml serialization)]
using System;;
First initialize a class and set the attribute value
var xmlDoc = new XmlDocument(); //Create the xml declaration first (("1.0", "utf-8", null)); //Create the root node and append into doc var el = ("Contacts"); (el); // Contact XmlElement elementContact = ("Contact"); XmlAttribute attrID = ("id"); = "01"; (attrID); (elementContact); // Contact Name XmlElement elementName = ("Name"); = "Daisy Abbey"; (elementName); // Contact Gender XmlElement elementGender = ("Gender"); = "female"; (elementGender); ("");
Create an XmlSerializer instance
class XXX { XmlSerializer ser = new XmlSerializer(("")); Truck tr = new Truck(); = 1; = "Gan A T34923"; }
Serialize method – complete serialization of classes
XmlTextWriter xtw = new XmlTextWriter("",Encoding.UTF8); useXmlTextWriter Create aXMLdocument (xtw, tr); //If you only want to display, you can directly (, tr);}
Common methods for xml:
Define xml document: XmlDocument xmlDoc = new XmlDocument();
Initialize the xml document: ("D:\");//Finish the xml file
Create root element: XmlElement xmlElement = ("", "Employees", "");
Create node: XmlElement xeSub1 = ("title");
Find Employees node: XmlNode root = ("Employees");
Add node: (xeSub1);
Change the properties of the node: ("Name", "Li Mingming");
Remove the ID attribute of xe: ("ID");
Delete the node title: (xe2);
Example: Write to xml
1. Create an XML document
public void CreateXMLDocument() { XmlDocument xmlDoc = new XmlDocument(); //Additional paragraph to add XML, <?xml version="1.0" encoding="gb2312"?> XmlDeclaration xmlDeclar; xmlDeclar = ("1.0", "gb2312", null); (xmlDeclar); //Add Employees root element XmlElement xmlElement = ("", "Employees", ""); (xmlElement); //Add node XmlNode root = ("Employees"); XmlElement xe1 = ("Node"); ("Name", "Salary Code"); ("ISB", "2-3631-4"); //Add child nodes XmlElement xeSub1 = ("title"); = "Learning VS"; (xeSub1); XmlElement xeSub2 = ("price"); (xeSub2); XmlElement xeSub3 = ("weight"); = "20"; (xeSub3); (xe1); ("D:\\");//Save path}
The generated xml file is as follows:
<?xml version="1.0" encoding="GB2312"?> -<Employees>- <Node ISB="2-3631-4" Name="Salary Code"> <title>studyVS</title>- <price> <weight>20</weight> </price> </Node> </Employees>
2. Add nodes
XmlDocument xmlDoc = new XmlDocument(); ("D:\\");//Finish the xml fileXmlNode root = ("Employees");//Find Employees nodeXmlElement xe1 = ("Node2");//Add Node2 node("Name", "Zhang Fei"); XmlElement xeSub1 = ("title");//Define child nodes = "Good mood"; (xeSub1);//Add node to Node2(xe1);//Add node to Employees("D:\\");
result:
<?xml version="1.0" encoding="GB2312"?> -<Employees> -<Node ISB="2-3631-4" Name="Salary Code"> <title>studyVS</title>- <price> <weight>20</weight> </price> </Node>- <Node2 Name="Zhang San"> <title>Good mood</title> </Node2>- <Node2 Name="Zhang San"> <title>Good mood</title> </Node2> </Employees>
3. Modify nodes:
public void ModifyNode() { XmlDocument xmlDocument = new XmlDocument(); ("D:\\"); XmlNodeList nodeList = ("Employees").ChildNodes;//Get all child nodes of Employees node foreach (XmlNode xn in nodeList)//Travel { XmlElement xe = (XmlElement)xn; if (("Name") == "Salary Code") { ("Name", "Salary");//Change the properties of the node XmlNodeList xnl = ;//Get all children of xe foreach (XmlNode xn1 in xnl) { XmlElement xe2 = (XmlElement)xn1;//Convert the attribute of node xn1 to XmlElement if ( == "title")//Find the node with the node name title { = "The weather today is bad"; } if ( == "price") { XmlNodeList xnl2 = ; foreach (XmlNode xn2 in xnl2) { if ( == "weight") { = "88"; } } } } } } ("D:\\"); }
Running results:
<?xml version="1.0" encoding="GB2312"?> -<Employees> -<Node ISB="2-3631-4" Name="Salary"> <title>The weather today is bad</title>-<price> <weight>88</weight> </price> </Node> -<Node2 Name="Zhang San"> <title>Good mood</title> </Node2></Employees>
4. Delete nodes
public void DeleteNode() { XmlDocument xmlDocument = new XmlDocument(); ("D:\\"); XmlNodeList xnl = ("Employees").ChildNodes; foreach (XmlNode xn in xnl) { if ( == "Node") { XmlElement xe = (XmlElement)xn;//Convert xn attribute to XmlElement ("ID");//Remove the ID attribute of xe XmlNodeList xnl2 = ; for (int i = 0; i < ; i++) { XmlElement xe2 = (XmlElement)(i); if ( == "title") { (xe2);//Delete the node title } } } } ("D:\\"); }
result:
<?xml version="1.0" encoding="GB2312"?> -<Employees> -<Node ISB="2-3631-4" Name="Salary">-<price> <weight>20</weight> </price> </Node>- <Node2 Name="Zhang San"> <title>Good mood</title> </Node2>- <Node2 Name="Zhang San"> <title>Good mood</title> </Node2> </Employees>
C# Read xml file
The xml file is as follows:
<?xml version="1.0" encoding="utf-8" ?> <configurationN> <ServerAddress>1143</ServerAddress> <ID>192.168</ID> </configurationN>
When writing to an XML file, two main methods are used: Load and Save.
Load: Initialize the xml document so that the project file can obtain the value of the specific xml node.
public void Load(string path) { try { XmlDocument xmlDocument = new XmlDocument(); (path); XmlNodeList xnl = (managerNode).ChildNodes; foreach (XmlNode xn in xnl) { if ( == configuration_ServerAddress) { ServerAddress = ; } } } catch(Exception ex) { } }
Save: After modifying the configuration file value in the project system, the XML needs to be saved again.
public void Save(string path) { try { XmlDocument xmlDocument = new XmlDocument(); (path); XmlNodeList xnl = (managerNode).ChildNodes; foreach (XmlNode xn in xnl) { if ( == configuration_ServerAddress) { = ServerAddress; } } (path); } catch (Exception ex) { } }
All the codes are posted here to facilitate the next implementation. Because the project is a WPF file and is all simple controls, only the background code is posted.
class ConfigurationManager:INotifyPropertyChanged { public const string managerNode = "configurationN";//Root node public const string configuration_ServerAddress = "ServerAddress";//Child node private string _ServerAddress; public string ServerAddress { get { return _ServerAddress; } set { _ServerAddress = value; NotifyPropertyChanged("ServerAddress"); } } public void Load(string path) { try { XmlDocument xmlDocument = new XmlDocument(); (path); XmlNodeList xnl = (managerNode).ChildNodes; foreach (XmlNode xn in xnl) { if ( == configuration_ServerAddress) { ServerAddress = ; } } } catch(Exception ex) { } } public void Save(string path) { try { XmlDocument xmlDocument = new XmlDocument(); (path); XmlNodeList xnl = (managerNode).ChildNodes; foreach (XmlNode xn in xnl) { if ( == configuration_ServerAddress) { = ServerAddress; } } (path); } catch (Exception ex) { } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public static ConfigurationManager Instance = new ConfigurationManager(); } public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Start(); this. = (); } private string path = "CONFIG\\"; private void button1_Click(object sender, RoutedEventArgs e) { = this.; (path); } private void button2_Click(object sender, RoutedEventArgs e) { (); } private void Start() { (path); } }
Summarize
This is the article about C# reading and writing xml file methods. For more related C# reading and writing xml file content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!