Home  >  Article  >  Backend Development  >  C# simple operation on xml

C# simple operation on xml

巴扎黑
巴扎黑Original
2017-05-21 13:56:441267browse

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 an attribute in the node

XmlDocument doc=new XmlDocument();  
doc.Load("config.xml");//可以再加入路径:如D:\config.xml  
XmlNode xnuser=doc.SelectSingleNode("userdata");  
string flag=xnuser.Attributes["createuser"].InnerText;

Read the value in the node

XmlDocument doc=new XmlDocument();  
doc.Load("config.xml");  
XmlNode xnserver = doc.SelectSingleNode("userdata/dataconnection/server");

Modify the attributes of the node

XmlDocument doc=new XmlDocument();  
doc.Load("config.xml");  
XmlNode xnuser=doc.SelectSingleNode("userdata");  
xnuser.Attributes["createuser"].InnerText="false";  
doc.Save("config.xml");

Append the node

XmlDocument doc = new XmlDocument();  
XmlTextReader reader = new XmlTextReader("config.xml");  
doc.Load("config.xml");  
XmlElement root = doc.DocumentElement; // 获取根节点  
XmlElement tagMessage = doc.CreateElement("net");  
XmlElement tagText = doc.CreateElement("name");  
tagText.InnerText = netname;  
tagMessage.AppendChild(tagText); // 追加到 xml 文本的最后面  
root.AppendChild(tagMessage);  
reader.Close(); // 关闭 XmlTextReader  
doc.Save("config.xml"); // 保存 xml 文件

The above is the detailed content of C# simple operation on xml. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn