Home  >  Article  >  Backend Development  >  XmlDocument sample code for operating xml documents

XmlDocument sample code for operating xml documents

黄舟
黄舟Original
2017-03-16 17:07:111708browse

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!

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