|
本帖最后由 笒羽 于 2015-3-3 10:35 编辑
一、web.config是什么文件?Web.config文件是一个XML文本文件,因此在C#代码表示对象为XmlDocument
二、加载XML文件
既然我们已经知道对象为XmlDocument,那么我们应该先实例化一个对象,然后加载XML文件内容,代码如下:- string XmlFilePath="d:\wwwroot\web.config";
- XmlDocument xdoc = new XmlDocument();
- xdoc.Load(XmlFilePath);
复制代码 三、节点、元素、属性
1、认识对象
XML文件的三个基本对象有节点(XmlNode)、元素(XmlElement)、属性(Attribute)
用以下XML文件内容为例:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="testAgentUser" value="1"/>
<add key="adminUser" value="babuyu"/>
</appSettings>
</configuration>
configuration、appSettings都是节点对象,它们有起始标记和闭合标记;configuration->appSettings->add为元素,configuration->appSettings->add->key为属性名、testAgentUser为属性值
2、获取节点,方法如下:- public XmlNode GetNode(string xPath)
- {
- string[] PathList = xPath.Trim('/').Split('/');
- XmlNode xn = xdoc.SelectSingleNode("/");
- string xnPath = "";
- for (int i = 0; i < PathList.Length; i++)
- {
- if (!string.IsNullOrEmpty(PathList[i]))
- {
- xnPath += "/" + PathList[i];
- XmlNode NowNode = xdoc.SelectSingleNode(xnPath);
- if (NowNode == null)
- {
- XmlNode newNode = xdoc.CreateNode(XmlNodeType.Element, PathList[i], null);
- xn.AppendChild(newNode);
- xn = xdoc.SelectSingleNode(xnPath);
- }
- else
- {
- xn = xdoc.SelectSingleNode(xnPath);
- }
- }
- }
- return xn;
- }
复制代码 得到节点对象后便可对其进行操作,如:xn.Attributes添加属性,xn.RemoveAll删除节点等,具体的请参考MSDN介绍:
https://msdn.microsoft.com/zh-cn/library/system.xml.xmlnode(VS.80).aspx
3、添加元素,方法如下:
XmlElement el = xdoc.CreateElement(ElementName);//创建元素
el.SetAttribute(s, v);//设置元素属性
xn.AppendChild(el);//将元素拼接到节点
4、保存XML文件编辑
xdoc.Save(FilePath);
|
|