场景:
1.有时候配置软件的全局设置项时,需要用到键值对的存储方式。
2.配置信息不多的情况下.数据库太重量级,文本文件对utf8编码又不好,即中文内容,这时候XML文件是最佳选择。
要求:
1.使用第3方库或windows SDK,更新某元素的属性值和元素值。
2.提供函数或方法.修改属性值和元素值。如:
复制代码
1.有时候配置软件的全局设置项时,需要用到键值对的存储方式。
2.配置信息不多的情况下.数据库太重量级,文本文件对utf8编码又不好,即中文内容,这时候XML文件是最佳选择。
要求:
1.使用第3方库或windows SDK,更新某元素的属性值和元素值。
2.提供函数或方法.修改属性值和元素值。如:
- <xml>
- <selectwindow>It is a select object window</selectwindow>
- <toolbarwindow name="toolbar" width="200">
- It is a toolbar.
- <rect x="4" y="5"/>
- </toolbarwindow >
1.实现函数 UpdateElementValue(const char* key,const char* value);
-- key的格式,更新toolbarwindow 属性name值时,可使用xpath格式,传入参数:toolbarwindow@name和值"goodbye"
-- 更新rect的属性值x时,key: "toolbarwindow:rect@x" value: "100"
using System;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xmlPath = "E:\\XMLFile1.xml";
Console.WriteLine("input the key:");
string key = Console.ReadLine();
Console.WriteLine("input the value:");
string val = Console.ReadLine();
string[] str = key.Split(':');
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
if (str.Length > 1)
{
string[] r = str[1].ToString().Split('@');
XmlNodeList nodeList = xmlDoc.SelectSingleNode(str[0].ToString()).ChildNodes;
foreach (XmlNode xn in nodeList)
{
if (xn.LocalName.ToString() == r[0].ToString())
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute(r[1].ToString()).ToString() != "")
{
xe.SetAttribute(r[1].ToString(), val);
}
}
}
xmlDoc.Save(xmlPath);
}
else
{
string[] r = key.Split('@');
XmlNode xn = xmlDoc.SelectSingleNode(r[0].ToString());
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute(r[1].ToString())!="")
{
xe.SetAttribute(r[1].ToString(), val);
}
xmlDoc.Save(xmlPath);
}
}
}
}