读取XML的内容
/// <summary>
/// 读取配置
/// </summary>
/// <param name="xmlFile"></param>
/// <returns></returns>
public static Dictionary<string, string> ReadConfig(XML文件的路径)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
XmlDocument xmlDoc = new XmlDocument();
xmlFile = LBFileSystem.ToAbsolutePath(xmlFile);
xmlDoc.Load(xmlFile);
XmlNodeList nodeList = xmlDoc.SelectSingleNode(ROOT_NODE_NAME).ChildNodes;//获取节点的所有子节点
foreach (XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe = xn as XmlElement;//将子节点类型转换为XmlElement类型
dict.Add(xe.Name, xe.InnerText);
}
return dict;
}
/// <summary>
/// 写入XML配置
/// </summary>
/// <param name="xmlFile"></param>
/// <param name="dict"></param>
/// <returns></returns>
public static bool WriteConfig(string xmlFile, Dictionary<string, string> dict)
{
XmlDocument xmldoc = new XmlDocument();
try
{
XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmldoc.AppendChild(xmldec);
XmlElement xmlele = xmldoc.CreateElement("", ROOT_NODE_NAME, "");
xmldoc.AppendChild(xmlele);
XmlNode root = xmldoc.SelectSingleNode(ROOT_NODE_NAME);
foreach (var item in dict)
{
xmlele = xmldoc.CreateElement(item.Key);
xmlele.InnerText = item.Value;
root.AppendChild(xmlele);
}
xmlFile = LBFileSystem.ToAbsolutePath(xmlFile);(转换成绝对路径)
xmldoc.Save(xmlFile);
return true;
}
catch (Exception)
{
return false;
}
}