C#针对xml基本操作及保存配置文件应用实例

  class ConfigurationManager:INotifyPropertyChanged

  {

  public const string managerNode = "configurationN";//根节点

  public const string configuration_ServerAddress = "ServerAddress";//子节点

  private string _ServerAddress;

  public string ServerAddress

  {

  get { return _ServerAddress; }

  set

  {

  _ServerAddress = value;

  NotifyPropertyChanged("ServerAddress");

  }

  }

  public void Load(string path)

  {

  try

  {

  XmlDocument xmlDocument = new XmlDocument();

  xmlDocument.Load(path);

  XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;

  foreach (XmlNode xn in xnl)

  {

  if (xn.Name == configuration_ServerAddress)

  {

  ServerAddress = xn.InnerText;

  }

  }

  }

  catch(Exception ex)

  { }

  }

  public void Save(string path)

  {

  try

  {

  XmlDocument xmlDocument = new XmlDocument();

  xmlDocument.Load(path);

  XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;

  foreach (XmlNode xn in xnl)

  {

  if (xn.Name == configuration_ServerAddress)

  {

  xn.InnerText = ServerAddress;

  }

  }

  xmlDocument.Save(path);

  }

  catch (Exception ex)

  { }

  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void NotifyPropertyChanged(string propertyName)

  {

  if (PropertyChanged != null)

  {

  PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

  }

  }

  public static ConfigurationManager Instance = new ConfigurationManager();

  }

  public partial class MainWindow : Window

  {

  public MainWindow()

  {

  InitializeComponent();

  Start();

  this.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString();

  }

  private string path = "CONFIGSystem.xml";

  private void button1_Click(object sender, RoutedEventArgs e)

  {

  ConfigurationManager.Instance.ServerAddress = this.tb1.Text;

  ConfigurationManager.Instance.Save(path);

  }

  private void button2_Click(object sender, RoutedEventArgs e)

  {

  Application.Current.Shutdown();

  }

  private void Start()

  {

  ConfigurationManager.Instance.Load(path);

  }

  }