C# 读写XML文件最简单方法
标签:cti ace inf nodelist name 方式 span const doc
C#史上最简单读写xml文件方式,创建控制台应用程序赋值代码,就可以运行,需要改动,请自行调整
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ConsoleApp1
{
class Program
{
public const String xmlPath = "info.xml";
static void Main(string[] args)
{
IDictionary> infos = new Dictionary>();
infos.Add("Evan", new Liststring>() { "123", "456" });
SaveXML(infos);
ReadXML();
Console.ReadKey();
}
public static void SaveXML(IDictionary> infos)
{
if (infos == null || infos.Count == 0)
{
return;
}
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.AppendChild(dec);
XmlElement _infos = xmlDoc.CreateElement("infos");
foreach (KeyValuePair> item in infos)
{
XmlElement info = xmlDoc.CreateElement("info");
XmlElement name = xmlDoc.CreateElement("file1");
name.InnerText = item.Key;
info.AppendChild(name);
XmlNode filelist = xmlDoc.CreateElement("filelist");
info.AppendChild(filelist);
foreach (String number in item.Value)
{
XmlElement filed = xmlDoc.CreateElement("filed");
filed.InnerText = number;
filelist.AppendChild(filed);
}
_infos.AppendChild(info);
}
xmlDoc.AppendChild(_infos);
xmlDoc.Save(xmlPath);
}
public static IDictionary> ReadXML()
{
IDictionary> infos = new Dictionary>();
if (File.Exists(xmlPath))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlNode xn = xmlDoc.SelectSingleNode("infos");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xnf in xnl)
{
XmlElement xe = (XmlElement)xnf;
XmlNode nameNode = xe.SelectSingleNode("file1");
string name = nameNode.InnerText;
Console.WriteLine(name);
XmlNode filelist = xe.SelectSingleNode("filelist");
List list = new Liststring>();
foreach (XmlNode item in filelist.ChildNodes)
{
list.Add(item.InnerText);
}
infos.Add(name, list);
}
}
return infos;
}
}
}
参考他人代码,再加以加工调整,从而提升自己!!!!!
C# 读写XML文件最简单方法
标签:cti ace inf nodelist name 方式 span const doc
原文地址:https://www.cnblogs.com/OmySql/p/12405569.html
评论