Home >Backend Development >XML/RSS Tutorial >XmlDocument sample code for operating xml documents
XmlDocumentSample code for operating xml document
<?xml version="1.0" encoding="utf-8"?> <userdata createuser="false"> <dataconnection> <server>xml test</server> <uid>sa</uid> <pwd>sa</pwd> </dataconnection> <net> <name>xml document</name> </net> </userdata>
Read an attribute in the node
XmlDocument doc=new XmlDocument(); doc.Load("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 attribute 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 XmlDocument sample code for operating xml documents. For more information, please follow other related articles on the PHP Chinese website!