Home > Backend Development > XML/RSS Tutorial > XmlDocument sample code for operating xml documents

XmlDocument sample code for operating xml documents

黄舟
Release: 2017-03-16 17:07:11
Original
1780 people have browsed it

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>
Copy after login

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;
Copy after login

Read the value in the node

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

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");
Copy after login

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 文件
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template