C#读写XML文件实例代码-创新互联
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 List() { "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 List();
foreach (XmlNode item in filelist.ChildNodes)
{
list.Add(item.InnerText);
}
infos.Add(name, list);
}
}
return infos;
}
}
} 另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章题目:C#读写XML文件实例代码-创新互联
本文来源:http://www.jxjierui.cn/article/ejeii.html


咨询
建站咨询
