读取,写入XML文件

操作XML配置文件
本文介绍如何使用C#读取和写入XML配置文件,包括选取特定节点和添加新节点的方法。

XML文件内容如下:site.config

 

ContractedBlock.gifExpandedBlockStart.gifCode
<?xml version="1.0" encoding="utf-8" ?>
<sites>
 
<site siteid="1" securitylevel=""  publickey="" publicandprivatekey="" fromurlkey="" cryptkeyfield="" ivkeyfield="">
 
</site>
 
<site siteid="2" securitylevel=""  publickey="" publicandprivatekey="" fromurlkey="" cryptkeyfield="" ivkeyfield="">
 
</site>
</sites>

 

读取XML

 

ContractedBlock.gifExpandedBlockStart.gifCode
string cfgPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sites.config");
XmlDocument doc 
= new XmlDocument();
doc.Load(cfgPath);
XmlElement root 
= doc.DocumentElement;//:获取文档的根 System.Xml.XmlElement。
XmlNode node = root.SelectSingleNode(string.Format("site[@siteid='{0}']", siteID));// 选择匹配 XPath 表达式的第一个 XmlNode。
XmlAttribute att = node.Attributes["publickey"];
if (att != null)
{
     _publicKey 
= att.Value;
}

 

写入XML

 

 

ContractedBlock.gifExpandedBlockStart.gifCode
string cfgPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sites.config");
XmlDocument doc 
= new XmlDocument();      
doc.Load(cfgPath);     
XmlElement root 
= doc.DocumentElement;
XmlNode node 
= doc.CreateElement("site");//创建创建具有指定名称的元素
XmlAttribute att = doc.CreateAttribute("siteid"); //创建属性
att.Value = _siteID;
node.Attributes.Append(att);

root.AppendChild(node);
doc.Save(cfgPath);

 

    

转载于:https://www.cnblogs.com/weichuo/archive/2008/11/06/1327965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值