c sharp simple operation on xml
- 2020-05-05 11:05:54
- OfStack
The xml file format is as follows:
< ?xml version="1.0" encoding="utf-8"? >
< userdata createuser="false" >
< dataconnection >
< server > localhost < /server >
< uid > sa < /uid >
< pwd > < /pwd >
< /dataconnection >
< net >
< name > jiayuan < /name >
< /net >
< /userdata >
Read a property
in the node XmlDocument doc=new XmlDocument();
doc. Load (" config xml "); // you can add paths like D:\ config.xml
XmlNode xnuser=doc.SelectSingleNode("userdata");
string flag=xnuser.Attributes["createuser"].InnerText;
Read the value
from the node XmlDocument doc=new XmlDocument();
doc.Load("config.xml");
XmlNode xnserver = doc.SelectSingleNode("userdata/dataconnection/server");
Modify the node's properties
XmlDocument doc=new XmlDocument();
doc.Load("config.xml");
XmlNode xnuser=doc.SelectSingleNode("userdata");
xnuser.Attributes["createuser"].InnerText="false";
doc.Save("config.xml");
Append node
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader("config.xml");
doc.Load("config.xml");
XmlElement root = doc DocumentElement; // gets the root node
XmlElement tagMessage = doc.CreateElement("net");
XmlElement tagText = doc.CreateElement("name");
tagText.InnerText = netname;
tagMessage. AppendChild (tagText); // is appended to the end of xml text
root.AppendChild(tagMessage);
reader. Close (); // close XmlTextReader
doc. Save (" config xml "); // save xml
< ?xml version="1.0" encoding="utf-8"? >
< userdata createuser="false" >
< dataconnection >
< server > localhost < /server >
< uid > sa < /uid >
< pwd > < /pwd >
< /dataconnection >
< net >
< name > jiayuan < /name >
< /net >
< /userdata >
Read a property
in the node XmlDocument doc=new XmlDocument();
doc. Load (" config xml "); // you can add paths like D:\ config.xml
XmlNode xnuser=doc.SelectSingleNode("userdata");
string flag=xnuser.Attributes["createuser"].InnerText;
Read the value
from the node XmlDocument doc=new XmlDocument();
doc.Load("config.xml");
XmlNode xnserver = doc.SelectSingleNode("userdata/dataconnection/server");
Modify the node's properties
XmlDocument doc=new XmlDocument();
doc.Load("config.xml");
XmlNode xnuser=doc.SelectSingleNode("userdata");
xnuser.Attributes["createuser"].InnerText="false";
doc.Save("config.xml");
Append node
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader("config.xml");
doc.Load("config.xml");
XmlElement root = doc DocumentElement; // gets the root node
XmlElement tagMessage = doc.CreateElement("net");
XmlElement tagText = doc.CreateElement("name");
tagText.InnerText = netname;
tagMessage. AppendChild (tagText); // is appended to the end of xml text
root.AppendChild(tagMessage);
reader. Close (); // close XmlTextReader
doc. Save (" config xml "); // save xml