XmlDocument 操作xml文档
有这样一段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>
读取节点中的一个属性
XmlDocument doc=new XmlDocument();
doc.Load("config.xml");
XmlNode xnuser=doc.SelectSingleNode("userdata");
string flag=xnuser.Attributes["createuser"].InnerText;
读取节点中的值
XmlDocument doc=new XmlDocument();
doc.Load("config.xml");
XmlNode xnserver = doc.SelectSingleNode("userdata/dataconnection/server");
修改节点的属性
XmlDocument doc=new XmlDocument();
doc.Load("config.xml");
XmlNode xnuser=doc.SelectSingleNode("userdata");
xnuser.Attributes["createuser"].InnerText="false";
doc.Save("config.xml");
追加节点
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 文件
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
读取节点中的一个属性
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
读取节点中的值
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
修改节点的属性
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
追加节点
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)