XmlConfig.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System.IO;
  2. using System.Xml;
  3. namespace LJLib.Tools.File
  4. {
  5. public class XmlConfig
  6. {
  7. /// <summary>
  8. /// 设置xml值
  9. /// </summary>
  10. /// <param name="xmlPath">xml文件名</param>
  11. /// <param name="section">段名</param>
  12. /// <param name="keyname">值名</param>
  13. /// <param name="value">取值</param>
  14. public void SetXmlFileValue(string xmlPath, string section, string keyname, string value)
  15. {
  16. FileStream file = System.IO.File.Open(xmlPath, FileMode.OpenOrCreate);
  17. XmlDocument xDoc = new XmlDocument();
  18. try
  19. {
  20. xDoc.Load(file);
  21. }
  22. catch (System.Exception)
  23. {
  24. xDoc.LoadXml("<sections/>");
  25. }
  26. file.Close();
  27. XmlNode xRoot = xDoc.DocumentElement;
  28. XmlElement xSection = (XmlElement)xRoot.SelectSingleNode("section[@name='" + section + "']");
  29. if (xSection == null)
  30. {
  31. xSection = xDoc.CreateElement("section");
  32. xSection.SetAttribute("name", section);
  33. xRoot.AppendChild(xSection);
  34. }
  35. XmlElement xElem = (XmlElement)xSection.SelectSingleNode("add[@key='" + keyname + "']");
  36. if (xElem != null)
  37. {
  38. xElem.SetAttribute("value", value);
  39. }
  40. else
  41. {
  42. XmlElement xTmpElem = xDoc.CreateElement("add");
  43. xTmpElem.SetAttribute("key", keyname);
  44. xTmpElem.SetAttribute("value", value);
  45. xSection.AppendChild(xTmpElem);
  46. }
  47. xDoc.Save(xmlPath);
  48. }
  49. /// <summary>
  50. /// 读取xml值
  51. /// </summary>
  52. /// <param name="xmlPath"></param>
  53. /// <param name="section"></param>
  54. /// <param name="keyname"></param>
  55. /// <param name="defaultValue"></param>
  56. /// <returns></returns>
  57. public string GetXmlFileValue(string xmlPath, string section, string keyname, string defaultValue)
  58. {
  59. if (!System.IO.File.Exists(xmlPath))
  60. {
  61. return defaultValue;
  62. }
  63. FileStream file = System.IO.File.OpenRead(xmlPath);
  64. XmlDocument xDoc = new XmlDocument();
  65. try
  66. {
  67. xDoc.Load(file);
  68. }
  69. catch (System.Exception)
  70. {
  71. xDoc.LoadXml("<sections/>");
  72. }
  73. file.Close();
  74. XmlNode xRoot = xDoc.DocumentElement;
  75. XmlElement xSection = (XmlElement)xRoot.SelectSingleNode("section[@name='" + section + "']");
  76. if (xSection == null)
  77. {
  78. return defaultValue;
  79. }
  80. XmlElement xElem = (XmlElement)xSection.SelectSingleNode("add[@key='" + keyname + "']");
  81. if (xElem == null)
  82. {
  83. return defaultValue;
  84. }
  85. else
  86. {
  87. return xElem.GetAttribute("value");
  88. }
  89. }
  90. }
  91. }