C#读写xml文件最简单方法(操作配置文件)
生活随笔
收集整理的這篇文章主要介紹了
C#读写xml文件最简单方法(操作配置文件)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
C#使用LINQ操作XML配置文件讀取寫入數(shù)據(jù)配置文件config.xml,xml文件如下:
1 view plaincopy to clipboardprint?
2 <?xml version="1.0" encoding="utf-8"?>
3 <Soft>
4 <SN RegCode="01234567890"></SN>
5 <LoginConfig SqlServer="." SqlDB="db" UserCode="sa" UserPwd="123">
6 </LoginConfig>
7 </Soft>
讀取指定元素指定屬性的值:
1 /// <summary>
2 /// 返回XMl文件指定元素的指定屬性值
3 /// </summary>
4 /// <param name="xmlElement">指定元素</param>
5 /// <param name="xmlAttribute">指定屬性</param>
6 /// <returns></returns>
7 public static string getXmlValue(string xmlElement,string xmlAttribute)
8 {
9 XDocument xmlDoc = XDocument.Load(xmlName);
10 var results = from c in xmlDoc.Descendants(xmlElement)
11 select c;
12 string s = "";
13 foreach (var result in results)
14 {
15 s = result.Attribute(xmlAttribute).Value.ToString();
16 }
17 return s;
18 }
寫入指定元素指定屬性的值:
1 /// <summary>
2 /// 設(shè)置XMl文件指定元素的指定屬性的值
3 /// </summary>
4 /// <param name="xmlElement">指定元素</param>
5 /// <param name="xmlAttribute">指定屬性</param>
6 /// <param name="xmlValue">指定值</param>
7 public static void setXmlValue(string xmlElement, string xmlAttribute, string xmlValue)
8 {
9 XDocument xmlDoc = XDocument.Load(xmlName);
10 xmlDoc.Element("Soft").Element(xmlElement).Attribute(xmlAttribute).SetValue(xmlValue);
11 xmlDoc.Save(xmlName);
12 }
13 }
轉(zhuǎn)載于:https://www.cnblogs.com/dinid/articles/2018874.html
總結(jié)
以上是生活随笔為你收集整理的C#读写xml文件最简单方法(操作配置文件)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c#重命名文件 - 抛弃MoveTo,而
- 下一篇: 队列不存在,或您没有足够的权限执行该操作