[C#] XML Read

  • 385
  • 0

摘要:[C#] XML Read


      public static string GetConfig(string PathFileName,string ParentTag, string ChildTag,string InnerText)
      {
         string RtnVal = "";
         //path
         //string cfgpath = System.Windows.Forms.Application.StartupPath + "/Config/Config.xml";
         string cfgpath = PathFileName;
         // load doc into string
         XmlDocument doc = new XmlDocument();
         try
         {
            doc.Load(cfgpath);
            XmlNode mainnode = doc.SelectSingleNode(ParentTag + "/" + ChildTag);
            //找不到node自已新增進去
            if (mainnode == null)
            {
               XmlNode root = doc.SelectSingleNode(ParentTag);
               //Create a new node.
               XmlElement tmpnode = doc.CreateElement(ChildTag);
               //default value
               tmpnode.InnerText = InnerText;
               //Console.WriteLine("Display the modified XML...");
               root.AppendChild(tmpnode);
               mainnode = tmpnode;
               doc.Save(cfgpath);
            }
            //回傳值
            RtnVal = mainnode.InnerText;
         }
         catch (Exception ex)
         {
            Console.WriteLine("ConfigSetting_GetConfig(),"+DateTime.Now.ToString("yyyyMMdd hh:mm:ss")+",Not Find \"" + ChildTag + "\" Node, Now Append \"" + ChildTag + "\" Node, " + ex.Message);
         }
         return RtnVal;
      }