1、文件夹的创建
static string CreateDirectory(string direct)
{
string path = Path.Combine(Environment.CurrentDirectory, direct);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return path;
}
2、XML文件的创建
static void CreateXmlFile(string path, string filename)
{
string file = Path.Combine(path, filename);
if (!File.Exists(file))
{
XmlDocument xml = new XmlDocument();
//create root node
XmlElement config = xml.CreateElement("Config");
xml.AppendChild(config);
//create a node
for(int i = 0; i < 8; i++)
{
XmlElement device = xml.CreateElement("Device"+i);
config.AppendChild(device);
XmlElement manual = xml.CreateElement("Manual");
manual.InnerText = "tiger";
chip.AppendChild(manual);
}
xml.Save(file);
}
}
3、XML文件的读和修改
private string root = "Modulation";
private string filename = Environment.CurrentDirectory + "/Plugins/SRAM.xml";
public Xml(string _filename, string _root)
{
root = _root;
filename = _filename;
}
public string read(string node, string key)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载Xml文件
XmlElement rootElem = doc.DocumentElement; //获取根节点
XmlNodeList Nodes = rootElem.GetElementsByTagName(node); //获取node子节点集合
foreach (XmlNode item in Nodes)
{
XmlNodeList tag = ((XmlElement)item).GetElementsByTagName(key); //获取age子XmlElement集合
if (tag.Count == 1)
{
string value = tag[0].InnerText;
return value;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
return "";
}
public void modify(string node, string key, string value)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
XmlElement rootElem = xmlDoc.DocumentElement; //获取根节点
XmlNodeList nodeList = rootElem.GetElementsByTagName(node); //获取node子节点集合
foreach (XmlNode xn in nodeList) //遍历所有子节点
{
XmlNodeList tag = ((XmlElement)xn).GetElementsByTagName(key); //获取age子XmlElement集合
if (tag.Count == 1)
{
tag[0].InnerText = value;
break;
}
}
xmlDoc.Save(filename); //保存。
}
4、程序调用
public Xml ml;
static void Main(string[] args)
{
string path = CreateDirectory(“user”);
CreateXmlFile(path, “demo.xml”);
xml = new Xml(Environment.CurrentDirectory + “/user/demo.xml”, “Config”);
string str = xml.read(“device0”, “ManualWrite”);
xml.modify(“device0”,“Manual”,“mouse”);
}